package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushSetEntity;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.enums.StarEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.help.ProGetHelp;
import com.xbongbong.paas.help.ProUpdateHelp;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.help.subform.WarehouseTeamTransferSubForm;
import com.xbongbong.paas.help.team.FormTeamSetHelp;
import com.xbongbong.paas.help.team.TeamUserHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.log.thread.LogThreadPoolBeanConfig;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.CoUserListDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.ClueRuleService;
import com.xbongbong.paas.service.CoUserService;
import com.xbongbong.paas.service.CustomerRuleService;
import com.xbongbong.paas.service.TransferBackRuleScriptService;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.service.dynamic.crm.strategy.CustomerDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.log.crm.operation.CompetitorOperationLogHandle;
import com.xbongbong.paas.service.log.crm.operation.ServiceProjectOperationLogHandle;
import com.xbongbong.paas.service.team.TeamDataHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.factory.TeamDataFactory;
import com.xbongbong.parent.interfaces.TeamStrategy;
import com.xbongbong.parent.interfaces.logger.OperationLogFactory;
import com.xbongbong.pro.competitor.pojo.dto.log.CompetitorRemoveVisibleLogDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.domain.entity.FormTeamSetEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicBackAndExitTeamDTO;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.FieldAdvanceOperationEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.UpdateCustomerTeamScenesEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessTypeErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormPatternEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.listbatch.pojo.ErrorMessagePojo;
import com.xbongbong.pro.listbatch.pojo.TeamBatchPojo;
import com.xbongbong.pro.listbatch.pojo.dto.BatchAddUserDTO;
import com.xbongbong.pro.listbatch.pojo.dto.ChangeMainDTO;
import com.xbongbong.pro.listbatch.pojo.dto.HandoverDTO;
import com.xbongbong.pro.message.constant.BomPushConstant;
import com.xbongbong.pro.message.constant.CluePushConstant;
import com.xbongbong.pro.message.constant.ContractPushConstant;
import com.xbongbong.pro.message.constant.CustomerPushConstant;
import com.xbongbong.pro.message.constant.DistributorPushConstant;
import com.xbongbong.pro.message.constant.OpportunityPushConstant;
import com.xbongbong.pro.message.constant.OrderPushConstant;
import com.xbongbong.pro.message.constant.ProductionOrderPushConstant;
import com.xbongbong.pro.message.constant.PurchasePushConstant;
import com.xbongbong.pro.message.constant.QuotationPushConstant;
import com.xbongbong.pro.message.constant.SupplierPushConstant;
import com.xbongbong.pro.message.constant.WorkOrderPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.model.PushSetModel;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.pushset.CluePushSet;
import com.xbongbong.pro.message.pushset.ContractPushSet;
import com.xbongbong.pro.message.pushset.CustomerPushSet;
import com.xbongbong.pro.message.pushset.OpportunityPushSet;
import com.xbongbong.pro.message.pushset.OrderPushSet;
import com.xbongbong.pro.message.pushset.QuotationPushSet;
import com.xbongbong.pro.message.pushset.WorkOrderPushSet;
import com.xbongbong.pro.product.pojo.dto.BeforeSaveMyTeamDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.TeamUpdateMidPOJO;
import com.xbongbong.pro.team.TeamVerifyDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.pro.user.pojo.UserTypePojo;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamAddDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamAddPushDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamBatchAddByOtherBusinessDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamBatchAddDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamBatchDeleteDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamBatchSaveDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamBatchUpdateDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamDelDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamDelPushDTO;
import com.xbongbong.pro.userteam.pojo.dto.UserTeamRealBatchAddDTO;
import com.xbongbong.pro.userteam.pojo.dto.VerifyUserTeamForImportDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ListBatchConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.BomUserEntity;
import com.xbongbong.saas.domain.entity.ClueRuleEntity;
import com.xbongbong.saas.domain.entity.ClueUserEntity;
import com.xbongbong.saas.domain.entity.CommonVisibleRangeTeamEntity;
import com.xbongbong.saas.domain.entity.ContactUserEntity;
import com.xbongbong.saas.domain.entity.ContractUserEntity;
import com.xbongbong.saas.domain.entity.CustomerRuleEntity;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.MarketActivityUserEntity;
import com.xbongbong.saas.domain.entity.OpportunityUserEntity;
import com.xbongbong.saas.domain.entity.PayBalanceEntity;
import com.xbongbong.saas.domain.entity.PayBalanceUserEntity;
import com.xbongbong.saas.domain.entity.PayPlanSheetUserEntity;
import com.xbongbong.saas.domain.entity.PayPlanUserEntity;
import com.xbongbong.saas.domain.entity.PaymentBalanceEntity;
import com.xbongbong.saas.domain.entity.PaymentBalanceUserEntity;
import com.xbongbong.saas.domain.entity.PaymentSheetUserEntity;
import com.xbongbong.saas.domain.entity.PaymentUserEntity;
import com.xbongbong.saas.domain.entity.ProductUserEntity;
import com.xbongbong.saas.domain.entity.ProductionOrderUserEntity;
import com.xbongbong.saas.domain.entity.PurchaseUserEntity;
import com.xbongbong.saas.domain.entity.QuotationUserEntity;
import com.xbongbong.saas.domain.entity.RefundUserEntity;
import com.xbongbong.saas.domain.entity.SupplierContactUserEntity;
import com.xbongbong.saas.domain.entity.SupplierUserEntity;
import com.xbongbong.saas.domain.entity.UserAndDepTeamEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.WarehouseUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowUserEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorUserEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.enums.ClueRuleChildEnum;
import com.xbongbong.saas.enums.ClueRuleEnum;
import com.xbongbong.saas.enums.CustomerRuleChildEnum;
import com.xbongbong.saas.enums.CustomerRuleEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.PayBalanceEnum;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentBalanceEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.subform.ContactTeamEnum;
import com.xbongbong.saas.enums.subform.ContractTeamEnum;
import com.xbongbong.saas.enums.subform.OpportunityTeamEnum;
import com.xbongbong.saas.enums.subform.PayBalanceTeamEnum;
import com.xbongbong.saas.enums.subform.PaymentBalanceTeamEnum;
import com.xbongbong.saas.enums.subform.PaymentTeamEnum;
import com.xbongbong.saas.enums.subform.QuotationTeamEnum;
import com.xbongbong.saas.enums.subform.SubFormTransferEnum;
import com.xbongbong.saas.factory.publicrule.CheckClueRuleGainRate;
import com.xbongbong.saas.factory.publicrule.CheckClueRulePrePrincipal;
import com.xbongbong.saas.factory.publicrule.CheckRuleGainRate;
import com.xbongbong.saas.factory.publicrule.CheckRuleMaxClueNum;
import com.xbongbong.saas.factory.publicrule.CheckRuleMaxCustomerNum;
import com.xbongbong.saas.factory.publicrule.CheckRulePrePrincipal;
import com.xbongbong.saas.factory.publicrule.CheckRuleUtil;
import com.xbongbong.saas.factory.publicrule.IOperateClueRuleValue;
import com.xbongbong.saas.factory.publicrule.IOperateRuleValue;
import com.xbongbong.saas.factory.publicrule.OperateClueRuleValueFactory;
import com.xbongbong.saas.factory.publicrule.OperateRuleValueFactory;
import com.xbongbong.saas.help.PublicSeniorRuleHelp;
import com.xbongbong.saas.help.SaasGetHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.BomUserModel;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.CompetitorUserModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContactUserModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CostAdjustModel;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.MarketActivityUserModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OpportunityUserModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.PayBalanceModel;
import com.xbongbong.saas.model.PayBalanceUserModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetUserModel;
import com.xbongbong.saas.model.PayPlanUserModel;
import com.xbongbong.saas.model.PaymentBalanceModel;
import com.xbongbong.saas.model.PaymentBalanceUserModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetUserModel;
import com.xbongbong.saas.model.PaymentUserModel;
import com.xbongbong.saas.model.ProductUserModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.ProductionOrderUserModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseUserModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.QuotationUserModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.RefundUserModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierContactUserModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.SupplierUserModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WarehouseUserModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFlowUserModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.team.UserAndDepTeamModel;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.paas.pojo.ServiceProjectVisibleLogDTO;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.join.query.HasChildQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.paas.constant.PaasConstant.DEFAULT_INITIAL_CAPACITY;
import static com.xbongbong.paas.elasticsearch.constant.EsNormalConstant.MINI_MUM_SHOULD_MATCH;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/2/19 18:57
 * @since v1.0
 */
@Service("userTeamService")
public class UserTeamServiceImpl implements UserTeamService {
    private static final Logger LOG = LoggerFactory.getLogger(UserTeamServiceImpl.class);
    @Resource
    private UserModel userModel;
    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private OpportunityUserModel opportunityUserModel;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    private ContactUserModel contactUserModel;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private ProGetHelp proGetHelp;
    @Resource
    private SupplierUserModel supplierUserModel;
    @Resource
    private PurchaseUserModel purchaseUserModel;
    @Resource
    private BomUserModel bomUserModel;
    @Resource
    private ProductionOrderUserModel productionOrderUserModel;
    @Resource
    private CustomerRuleService customerRuleService;
    @Resource
    private PaymentUserModel paymentUserModel;
    @Resource
    private RefundUserModel refundUserModel;
    @Resource
    private PayPlanUserModel payPlanUserModel;
    @Resource
    private SupplierContactUserModel supplierContactUserModel;
    @Resource
    private ProductUserModel productUserModel;
    @Resource
    private WarehouseUserModel warehouseUserModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private SaasGetHelp saasGetHelp;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private WorkOrderFlowUserModel workOrderFlowUserModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private CustomerModel customerModel;
    @Resource
    @Lazy
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private CoUserService coUserService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private QuotationUserModel quotationUserModel;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private UserService userService;
    @Resource
    private PaymentBalanceUserModel paymentBalanceUserModel;
    @Resource
    private PayBalanceUserModel payBalanceUserModel;
    @Resource
    private PaymentBalanceModel paymentBalanceModel;
    @Resource
    private PayBalanceModel payBalanceModel;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaymentSheetUserModel paymentSheetUserModel;
    @Resource
    private PayPlanSheetUserModel payPlanSheetUserModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private CheckRuleMaxCustomerNum checkRuleMaxCustomerNum;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private ProUpdateHelp proUpdateHelp;
    @Resource
    private LogThreadPoolBeanConfig logThreadPoolBeanConfig;
    @Resource
    private PushSetModel pushSetModel;
    @Resource
    private ClueUserModel clueUserModel;
    @Resource
    private MarketActivityUserModel marketActivityUserModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private CheckRuleMaxClueNum checkRuleMaxClueNum;
    @Resource
    private ClueRuleService clueRuleService;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private CostAdjustModel costAdjustModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private CompetitorUserModel competitorUserModel;

    @Resource
    private TeamDataFactory teamDataFactory;
    @Resource
    private TeamDataHelp teamDataHelp;
    @Resource
    private WarehouseTeamTransferSubForm warehouseTeamTransferSubForm;
    @Resource
    private FormTeamSetHelp formTeamSetHelp;
    @Resource
    private PublicSeniorRuleHelp publicSeniorRuleHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private TeamUserHelp teamUserHelp;
    @Resource
    private TransferBackRuleScriptService transferBackRuleScriptService;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;
    @Resource
    private OperationLogFactory operationLogFactory;
    @Resource
    private UserAndDepTeamModel userAndDepTeamModel;

    private final static Integer MAIN_USER = 1;
    private final static Integer CO_USER = 0;


    @Override
    public BaseVO add(UserTeamAddDTO userTeamAddDTO) throws XbbException {
        String corpid = userTeamAddDTO.getCorpid();
        String userId = userTeamAddDTO.getTeamUserId();
        Long dataId = userTeamAddDTO.getDataId();
        Integer businessType = userTeamAddDTO.getBusinessType();
        addMainUser(corpid, businessType, userId, dataId, userTeamAddDTO.getIsMain());
        UserTeamAddPushDTO userTeamAddPushDTO = new UserTeamAddPushDTO();
        BeanUtil.copyProperties(userTeamAddDTO, userTeamAddPushDTO);
        pushMessageAfterAddUser(userTeamAddPushDTO);
        return new BaseVO();
    }

    @Override
    public void disbandedCustomerTeam(String corpid, List<Long> customerIdList) throws XbbException{
        //解散客户团队的同时解散合同机会联系人回款退货退款团队
        customerUserModel.disbandedTeam(corpid, customerIdList, null);
        contractUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        opportunityUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        contactUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        quotationUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        paymentBalanceUserModel.disbandedTeamByCustomerId(corpid,customerIdList);
//        paymentUserModel.disbandedTeamByCustomerId(corpid,customerIdList);
//        refundUserModel.disbandedTeamByCustomerId(corpid,customerIdList);
    }

    @Override
    public void disbandedOtherUser(String corpid, List<Long> customerIdList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        contractUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        opportunityUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        contactUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        quotationUserModel.disbandedTeamByCustomerId(corpid, customerIdList);
        paymentBalanceUserModel.disbandedTeamByCustomerId(corpid,customerIdList);
    }

    @Override
    public BaseVO delete(UserTeamDelDTO userTeamDelDTO) throws XbbException {
        String corpid = userTeamDelDTO.getCorpid();
        String userId = userTeamDelDTO.getUserId();
        Long teamUserId = userTeamDelDTO.getTeamUserId();
        Long dataId = userTeamDelDTO.getDataId();
        Integer businessType = userTeamDelDTO.getBusinessType();
        String deleteUserId = deleteUser(corpid, userId, dataId, teamUserId, businessType);
        if (StringUtil.isNotEmpty(deleteUserId)) {
            UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
            if (userTeamEnum == UserTeamEnum.CUSTOMER_TEAM) {
                // 去除客户标签
                boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
                CustomerEntityExt customerEntity = customerModel.getByKey(dataId, corpid);
                Long customerFormId  = customerEntity != null ? customerEntity.getFormId() : 0L;
                if (customerSeniorModel){
                    transferBackRuleScriptService.deletePublicSeniorTag(corpid,Collections.singletonList(dataId),XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),customerFormId);
                }else {
                    customerRuleService.deletePublicTag(corpid, Collections.singletonList(dataId));
                }
            }
            UserTeamDelPushDTO userTeamDelPushDTO = new UserTeamDelPushDTO();
            BeanUtil.copyProperties(userTeamDelDTO, userTeamDelPushDTO);
            userTeamDelPushDTO.setUpdateUserIdIn(Collections.singletonList(deleteUserId));
            pushMessageAfterRemoveUser(userTeamDelPushDTO);
        }
        return new BaseVO();
    }

    /**
     * 删除团队成员，业务区分
     *
     * @param corpid       公司id
     * @param userId       操作人id
     * @param dataId       业务数据id
     * @param teamUserId   被删除人协同团队表id
     * @param businessType 业务类型
     * @throws XbbException 异常
     * @return 删除的团队成员的用户id
     */
    private String deleteUser(String corpid, String userId, Long dataId, Long teamUserId, Integer businessType) throws XbbException {
        //TODO haibin.zhang 日志
        String deleteUserId = null;
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                deleteUserId = deleteCustomerUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case CONTRACT_TEAM:
                deleteUserId = deleteContractUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case OPPORTUNITY_TEAM:
                deleteUserId = deleteOpportunityUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case BOMBILL_TEAM:
                deleteUserId = deleteBombillUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case PRODUCTIONORDER_TEAM:
                deleteUserId = deleteProductionUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case PURCHASE_TEAM:
                deleteUserId = deletePurchaseUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case SUPPLIER_TEAM:
                deleteUserId = deleteSupplierUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case PRODUCT_TEAM:
                deleteProductUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case REFUND_TEAM:
                deleteRefundUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case WORK_ORDER_TEAM:
                deleteUserId = deleteWorkOrderUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case QUOTATION_TEAM:
                deleteQuotationUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case COMPETITOR_TEAM:
                deleteCompetitorUser(corpid, dataId, userId, teamUserId, businessType);
                break;
            case SERVICE_PROJECT_TEAM:
                deleteServiceProjectUser(corpid, dataId, userId, teamUserId, businessType);
            default:
                break;
        }
        return deleteUserId;
    }

    /**
     * Description:删除工单人员
     * @param corpid
     * @param dataId
     * @param userId
     * @param teamUserId
     * @param businessType
     * @return java.lang.String
     * @author 魏荣杰
     * @date 2019/5/7 14:43
     * @since v1.0
     */
    private String deleteWorkOrderUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException {
        WorkOrderFlowUserEntity workOrderFlowUserEntity = workOrderFlowUserModel.getByKey(teamUserId, corpid);
        if (workOrderFlowUserEntity == null || workOrderFlowUserEntity.getDel() == 1) {
            return null;
        }
        workOrderFlowUserModel.delete(workOrderFlowUserEntity);
        return workOrderFlowUserEntity.getUserId();
    }

    /**
     * Description: 删除报价单人员
     * @param corpid
     * @param dataId
     * @param userId
     * @param teamUserId
     * @param businessType
     * @return java.lang.String
     * @throws XbbException
     * @author 刘阳
     * @date 2019/8/16 2:45 PM
     * @since v1.0
     */
    private String deleteQuotationUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException {
        QuotationUserEntity quotationUserEntity = quotationUserModel.getByKey(teamUserId, corpid);
        if (quotationUserEntity == null || quotationUserEntity.getDel() == 1) {
            return null;
        }
        quotationUserModel.delete(quotationUserEntity);
        return quotationUserEntity.getUserId();
    }

    private void deleteCompetitorUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException {
        CompetitorUserEntity competitorUserEntity = competitorUserModel.getByKey(teamUserId, corpid);
        if (competitorUserEntity == null || competitorUserEntity.getDel() == 1) {
            return;
        }
        competitorUserModel.delete(competitorUserEntity);
        //日志记录
        afterDeleteCompetitorUser(corpid,userId,competitorUserEntity,businessType);
    }

    /**
     * 服务项目移除可见人、可见部门
     * @param corpid
     * @param dataId
     * @param userId
     * @param teamUserId
     * @param businessType
     */
    private void deleteServiceProjectUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) {
        CommonVisibleRangeTeamEntity serviceProjectUserEntity = userAndDepTeamModel.getByKey(teamUserId,corpid, "tb_work_order_v2_service_project_user");
        if (Objects.isNull(serviceProjectUserEntity)) {
            return;
        }
        userAndDepTeamModel.deleteByKey(serviceProjectUserEntity.getId(), serviceProjectUserEntity.getCorpid(), "tb_work_order_v2_service_project_user");
        //日志记录
        afterDeleteServiceProjectUser(corpid, userId, serviceProjectUserEntity, businessType);
    }

    /**
     * 服务项目移除可见人、可见部门日志
     * @param corpid
     * @param userId
     * @param serviceProjectUserEntity
     * @param businessType
     */
    private void afterDeleteServiceProjectUser(String corpid, String userId, CommonVisibleRangeTeamEntity serviceProjectUserEntity, Integer businessType) {

        Runnable runnable = () -> {
            try {
                Integer type = serviceProjectUserEntity.getType();
                Long dataId = serviceProjectUserEntity.getDataId();
                String relationId = serviceProjectUserEntity.getRelationId();
                UserEntity userEntity = userModel.getByKey(userId, corpid);
                String userName = userEntity.getName();
                ServiceProjectVisibleLogDTO logDTO = new ServiceProjectVisibleLogDTO();
                logDTO.setCorpid(corpid);
                logDTO.setDataIdList(Collections.singletonList(dataId));
                logDTO.setRelationIdList(Collections.singletonList(relationId));
                logDTO.setUserId(userId);
                logDTO.setLoginUserName(userName);

                ServiceProjectOperationLogHandle logHandle = (ServiceProjectOperationLogHandle) operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(), businessType);
                if (Objects.nonNull(logHandle)) {
                    if (Objects.equals(type, 0)) {
                        logHandle.removeServiceProjectUser(logDTO);
                    } else if (Objects.equals(type, 1)) {
                        logHandle.removeServiceProjectDep(logDTO);
                    }
                }
            } catch (Exception e) {
                LOG.error("UserTeamServiceImpl#afterDeleteServiceProjectUser exception:{}", e);
            }
        };
        threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
    }

    /**
     * 竞争对手移除可见人、可见部门日志
     * @param corpid
     * @param userId
     * @param competitorUserEntity
     * @param businessType
     */
    private void afterDeleteCompetitorUser(String corpid,String userId,CompetitorUserEntity competitorUserEntity,Integer businessType){

        Runnable runnable = () -> {
            try {
                Integer type = competitorUserEntity.getType();
                Long dataId = competitorUserEntity.getDataId();
                String relationId = competitorUserEntity.getRelationId();
                UserEntity userEntity = userModel.getByKey(userId, corpid);
                String userName = userEntity.getName();
                CompetitorRemoveVisibleLogDTO logDTO = new CompetitorRemoveVisibleLogDTO();
                logDTO.setCorpid(corpid);
                logDTO.setDataIdList(Collections.singletonList(dataId));
                logDTO.setRelationIdList(Collections.singletonList(relationId));
                logDTO.setUserId(userId);
                logDTO.setLoginUserName(userName);

                CompetitorOperationLogHandle logHandle = (CompetitorOperationLogHandle) operationLogFactory.getOperationLogHandle(SaasMarkEnum.SAAS.getCode(), businessType);
                if (Objects.nonNull(logHandle)) {
                    if (Objects.equals(type,0)){
                        logHandle.removeCompetitorUser(logDTO);
                    }else if(Objects.equals(type,1)){
                        logHandle.removeCompetitorDep(logDTO);
                    }
                }
            }catch (Exception e){
                LOG.error("UserTeamServiceImpl#afterDeleteCompetitorUser exception:{}",e);
            }
        };

        threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);



    }

    /**
     * 删除退货退款团队成员
     */
    private void deleteRefundUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException {
        RefundUserEntity refundUser = refundUserModel.getByKey(teamUserId, corpid);
        if (refundUser == null || refundUser.getDel() == 1) {
            return;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(refundUser, userEntity, businessType, dataId);
        refundUserModel.delete(refundUser);
    }

    private void deleteProductUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException{
        ProductUserEntity productUserEntity = productUserModel.getByKey(teamUserId, corpid);
        if (productUserEntity == null || productUserEntity.getDel() == 1) {
            return;
        }
        Long productId = null;
        if (Objects.isNull(productUserEntity.getParentId()) || Objects.equals(productUserEntity.getParentId(),0L)){
            // 重复的父产品数据一次删除
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(StringConstant.CORPID,corpid);
            map.put(StringConstant.DEL,DelEnum.NORMAL.getDel());
            map.put("type",productUserEntity.getType());
            map.put("relationId",productUserEntity.getRelationId());
            map.put("dataId",productUserEntity.getDataId());
            List<UserAndDepTeamEntity> spuUserList = productUserModel.findBaseEntitys(map);
            List<Long> delList = new ArrayList<>();
            spuUserList.forEach(item -> delList.add(item.getId()));
            productUserModel.deleteByParentIdInAndRelationIdIn(corpid, Collections.singletonList(productUserEntity.getDataId()), Collections.singletonList(productUserEntity.getRelationId()), productUserEntity.getType(), delList);
            productId = productUserEntity.getDataId();
        } else {
            productUserModel.delete(productUserEntity);
            productId = productUserEntity.getParentId();
        }
    }

    private String deleteSupplierUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException{
        SupplierUserEntity supplierUserEntity = supplierUserModel.getByKey(teamUserId, corpid);
        if (supplierUserEntity == null || supplierUserEntity.getDel() == 1) {
            return null;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(supplierUserEntity, userEntity, businessType, dataId);
        supplierUserModel.delete(supplierUserEntity);
        deleteContactUserBySupplierId(corpid, dataId, supplierUserEntity.getUserId());
        return supplierUserEntity.getUserId();
    }

    private void deleteContactUserBySupplierId(String corpid, Long supplierId, String userId) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.SUPPLIER_CONTACT.getCode(), SupplierContactEnum.SUPPLIER_ID.getAttr(), supplierId, param, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
        List<Long> contactIds = new ArrayList<>();
        contactIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> contactIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("contactIdIn", contactIds);
        List<SupplierContactUserEntity> entitys = supplierContactUserModel.findEntitys(param);
        entitys.forEach(supplierContactUserEntity -> {
            try {
                supplierContactUserModel.delete(supplierContactUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    private String deletePurchaseUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException{
        PurchaseUserEntity purchaseUserEntity = purchaseUserModel.getByKey(teamUserId, corpid);
        if (purchaseUserEntity == null || purchaseUserEntity.getDel() == 1) {
            return null;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(purchaseUserEntity, userEntity, businessType, dataId);
        purchaseUserModel.delete(purchaseUserEntity);
        deletePayPlanUserByPurchaseId(corpid, dataId, purchaseUserEntity.getUserId());
        return purchaseUserEntity.getUserId();
    }

    private void deletePayPlanUserByPurchaseId(String corpid, Long purchaseId, String userId) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.PAY_PLAN.getCode(), PayPlanEnum.LINK_PURCHASE.getAttr(), purchaseId, param, IndexTypeEnum.IDX_SAAS_PAY_PLAN);
        List<Long> payPlanIds = new ArrayList<>();
        payPlanIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> payPlanIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("payPlanIdIn", payPlanIds);
        List<PayPlanUserEntity> entitys = payPlanUserModel.findEntitys(param);
        entitys.forEach(payPlanUserEntity -> {
            try {
                payPlanUserModel.delete(payPlanUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    private String deleteProductionUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException{
        ProductionOrderUserEntity productionOrderUserEntity = productionOrderUserModel.getByKey(teamUserId, corpid);
        if (productionOrderUserEntity == null || productionOrderUserEntity.getDel() == 1) {
            return null;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(productionOrderUserEntity, userEntity, businessType, dataId);
        productionOrderUserModel.delete(productionOrderUserEntity);
        return productionOrderUserEntity.getUserId();
    }

    private String deleteBombillUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException{
        BomUserEntity bomUserEntity = bomUserModel.getByKey(teamUserId, corpid);
        if (bomUserEntity == null || bomUserEntity.getDel() == 1) {
            return null;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(bomUserEntity, userEntity, businessType, dataId);
        bomUserModel.delete(bomUserEntity);
        return bomUserEntity.getUserId();
    }

    private void deleteContactUserByCustomerId(String corpid, Long customerId, String userId) throws XbbException {
       contactUserModel.deleteByUserIdAndCustomerId(corpid, customerId, userId);
    }

    /**
     * 删除客户团队成员
     */
    private String deleteCustomerUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException {
        CustomerUserEntity customerUser = customerUserModel.getByKey(teamUserId, corpid);
        if (customerUser == null || customerUser.getDel() == 1) {
            return null;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(customerUser, userEntity, businessType, dataId);
        customerUserModel.delete(customerUser);
        //解除关注
        customerFocusModel.unFocus(dataId, corpid, customerUser.getUserId());
        // 删除联系人团队
        deleteContactUserByCustomerId(corpid, dataId, customerUser.getUserId());
        deleteContractUserByCustomerId(corpid, dataId, customerUser.getUserId());
        deleteOpportunityUserByCustomerId(corpid, dataId, customerUser.getUserId());
        deletePaymentUserByCustomerId(corpid, dataId, customerUser.getUserId());
        deleteRefundUserByCustomerId(corpid, dataId, customerUser.getUserId());
        return customerUser.getUserId();
    }

    private void deleteRefundUserByCustomerId(String corpid, Long customerId, String userId) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.REFUND.getCode(), RefundEnum.CUSTOMER_ID.getAttr(), customerId, param, IndexTypeEnum.IDX_SAAS_REFUND);
        List<Long> refundIds = new ArrayList<>();
        refundIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> refundIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("refundIdIn", refundIds);
        List<RefundUserEntity> entitys = refundUserModel.findEntitys(param);
        entitys.forEach(refundUserEntity -> {
            try {
                refundUserModel.delete(refundUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    private void deletePaymentUserByCustomerId(String corpid, Long customerId, String userId) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.PAYMENT.getCode(), PaymentEnum.CUSTOMER.getAttr(), customerId, param, IndexTypeEnum.IDX_SAAS_PAYMENT);
        List<Long> paymentIds = new ArrayList<>();
        paymentIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> paymentIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("paymentIdIn", paymentIds);
        List<PaymentUserEntity> entitys = paymentUserModel.findEntitys(param);
        entitys.forEach(paymentUserEntity -> {
            try {
                paymentUserModel.delete(paymentUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    private void deleteOpportunityUserByCustomerId(String corpid, Long customerId, String userId) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.SALES_OPPORTUNITY.getCode(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), customerId, param, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        List<Long> opportunityIds = new ArrayList<>();
        opportunityIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> opportunityIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("opportunityIdIn", opportunityIds);
        List<OpportunityUserEntity> entitys = opportunityUserModel.findEntitys(param);
        entitys.forEach(opportunityUserEntity -> {
            try {
                opportunityUserModel.delete(opportunityUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    private void deleteContractUserByCustomerId(String corpid, Long customerId, String userId) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.CONTRACT.getCode(), ContractEnum.LINK_CUSTOMER.getAttr(), customerId, param, IndexTypeEnum.IDX_SAAS_CONTRACT);
        List<Long> contractIds = new ArrayList<>();
        contractIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> contractIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("contractIdIn", contractIds);
        List<ContractUserEntity> entitys = contractUserModel.findEntitys(param);
        entitys.forEach(contractUserEntity -> {
            try {
                contractUserModel.delete(contractUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 删除合同团队成员
     */
    private String deleteContractUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException {
        ContractUserEntity contractUser = contractUserModel.getByKey(teamUserId, corpid);
        if (contractUser == null || contractUser.getDel() == 1) {
            return null;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(contractUser, userEntity, businessType, dataId);
        contractUserModel.delete(contractUser);
        deletePaymentUserByContractId(corpid, dataId, contractUser.getUserId());
        deleteRefundUserByContractId(corpid, dataId, contractUser.getUserId());
        return contractUser.getUserId();
    }

    private void deleteRefundUserByContractId(String corpid, Long contractId, String userId) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.REFUND.getCode(), RefundEnum.CONTRACT_ID.getAttr(), contractId, param, IndexTypeEnum.IDX_SAAS_REFUND);
        List<Long> refundIds = new ArrayList<>();
        refundIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> refundIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("refundIdIn", refundIds);
        List<RefundUserEntity> entitys = refundUserModel.findEntitys(param);
        entitys.forEach(refundUserEntity -> {
            try {
                refundUserModel.delete(refundUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    private void deletePaymentUserByContractId(String corpid, Long contractId, String userId) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.PAYMENT.getCode(), PaymentEnum.CONTRACT.getAttr(), contractId, param, IndexTypeEnum.IDX_SAAS_PAYMENT);
        List<Long> paymentIds = new ArrayList<>();
        paymentIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> paymentIds.add(paasFormDataEntityExt.getId())));
        param.put(ParameterConstant.USER_ID, userId);
        param.put("paymentIdIn", paymentIds);
        List<PaymentUserEntity> entitys = paymentUserModel.findEntitys(param);
        entitys.forEach(paymentUserEntity -> {
            try {
                paymentUserModel.delete(paymentUserEntity);
            } catch (XbbException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 删除机会团队成员
     */
    private String deleteOpportunityUser(String corpid, Long dataId, String userId, Long teamUserId, Integer businessType) throws XbbException {
        OpportunityUserEntity opportunityUser = opportunityUserModel.getByKey(teamUserId, corpid);
        if (opportunityUser == null || opportunityUser.getDel() == 1) {
            return null;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        delRelated(opportunityUser, userEntity, businessType, dataId);
        opportunityUserModel.delete(opportunityUser);
        return opportunityUser.getUserId();
    }


    /**
     * 是否能删除团队成员
     * 原saas逻辑
     * 1、非超管只有负责人能删协同人
     * 2、非超管就算是负责人也不能删其他负责人
     * 3、就算是超管也不能删除唯一的负责人
     * 改写逻辑
     * 1、协同人超管或负责人可以删
     * 2、负责人超管可以删
     * 3、唯一负责人不能删
     *
     * @param userTeamEntity 团队成员基础实体
     * @param userEntity     操作人
     * @param businessType   业务
     * @param dataId     被删除人
     * @throws XbbException 各种没权限的错误提示
     */
    private void delRelated(UserTeamEntity userTeamEntity, UserEntity userEntity, Integer businessType, Long dataId) throws XbbException {
        Boolean isMain = Objects.equals(userTeamEntity.getIsMain(), 1);
        Boolean isBoss = userEntity.isOriAdmin();
        Integer countCompare = 0;
        Map<String, Object> map = new HashMap<>(16);
        map.put("corpid", userEntity.getCorpid());
        map.put("isMain", 1);
        map.put("del", 0);
        if (isMain) {
            if (!isBoss) {
                //非超管不能删除负责人
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390001);
            }
            //负责人大于1才能删除
            countCompare = 1;
        } else {
            if (isBoss) {
                //超管可以删除协同人
                return;
            }
            //非超管，负责人可以删除协同人
            map.put("userId", userEntity.getUserId());
        }
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        Boolean hasPermission;
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                map.put("customerId", dataId);
                hasPermission = customerUserModel.getEntitysCount(map) > countCompare;
                break;
            case CONTRACT_TEAM:
                map.put("contractId", dataId);
                hasPermission = contractUserModel.getEntitysCount(map) > countCompare;
                break;
            case OPPORTUNITY_TEAM:
                map.put("opportunityId", dataId);
                hasPermission = opportunityUserModel.getEntitysCount(map) > countCompare;
                break;
            case SUPPLIER_TEAM:
                map.put("supplierId", dataId);
                hasPermission = supplierUserModel.getEntitysCount(map) > countCompare;
                break;
            case PURCHASE_TEAM:
                map.put("purchaseId", dataId);
                hasPermission = purchaseUserModel.getEntitysCount(map) > countCompare;
                break;
            case PRODUCTIONORDER_TEAM:
                map.put("productionOrderId", dataId);
                hasPermission = productionOrderUserModel.getEntitysCount(map) > countCompare;
                break;
            case BOMBILL_TEAM:
                map.put("bomId", dataId);
                hasPermission = bomUserModel.getEntitysCount(map) > countCompare;
                break;
            case REFUND_TEAM:
                map.put("refundId", dataId);
                hasPermission = refundUserModel.getEntitysCount(map) > countCompare;
                break;
            case QUOTATION_TEAM:
                map.put("quotationId", dataId);
                hasPermission = quotationUserModel.getEntitysCount(map ) > countCompare;
                break;
            default:
                throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        if (!hasPermission) {
            if (isMain) {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390002);
            } else {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390003);
            }
        }

    }

    /**
     * 添加协同团队
     *
     * @param corpid       公司id
     * @param businessType 业务类型
     * @param userId       用户
     * @param dataId       协同团队表数据id
     * @param isMain       负责协同
     * @throws XbbException
     */
    private void addMainUser(String corpid, Integer businessType, String userId, Long dataId, Integer isMain) throws XbbException {
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                addCustomerUser(corpid, userId, dataId, isMain,businessType);
                addContactUserByCustomerId(corpid, userId, dataId, isMain);
                addContractUserByCustomerId(corpid, userId, dataId, isMain);
                addOpportunityUserByCustomerId(corpid, userId, dataId, isMain);
                addPaymentUserByCustomerId(corpid, userId, dataId, isMain);
                addQuotationUserByCustomerId(corpid, userId, dataId, isMain);
//                addRefundUserByCustomerId(corpid, userId, dataId, isMain);
                // 去除客户标签
                boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
                CustomerEntityExt customerEntity = customerModel.getByKey(dataId, corpid);
                Long customerFormId  = customerEntity != null ? customerEntity.getFormId() : 0L;
                if (customerSeniorModel){
                    transferBackRuleScriptService.deletePublicSeniorTag(corpid,Collections.singletonList(dataId),XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),customerFormId);
                }else {
                    customerRuleService.deletePublicTag(corpid, Collections.singletonList(dataId));
                }
                break;
            case CONTRACT_TEAM:
                addContractUser(corpid, userId, dataId, isMain);
                addPaymentUserByContractId(corpid, userId, dataId, isMain);
//                addRefundUserByContractId(corpid, userId, dataId, isMain);
                break;
            case OPPORTUNITY_TEAM:
                addOpportunityUser(corpid, userId, dataId, isMain);
                break;
            case QUOTATION_TEAM:
                addQuotationUser(corpid, userId, dataId, isMain);
                break;
            case CONTACT_TEAM:
                addContactUser(corpid, userId, dataId, isMain);
                break;
            case SUPPLIER_TEAM:
                addSuplierUser(corpid, userId, dataId, isMain);
                addContactUserBySupplierId(corpid, userId, dataId, isMain);
                break;
            case PURCHASE_TEAM:
                addPurchaseUser(corpid, userId, dataId, isMain);
                addPayPlanUserByPurchaseId(corpid, userId, dataId, isMain);
                break;
            case BOMBILL_TEAM:
                addBomBillUser(corpid, userId, dataId, isMain);
                break;
            case PRODUCTIONORDER_TEAM:
                addProductionOrderUser(corpid, userId, dataId, isMain);
                break;
            case REFUND_TEAM:
                addRefundUserByRefundId(corpid, userId, dataId, isMain);
                break;
            case WORK_ORDER_TEAM:
                addWorkOrderUser(corpid, userId, dataId, isMain);
                break;
            default:
                break;
        }
    }


    /**
     * 添加协同团队
     *
     * @param userTeamBatchAddDTO
     * @throws XbbException
     */
    private void batchAddMainUser(UserTeamBatchAddDTO userTeamBatchAddDTO) throws XbbException {
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(userTeamBatchAddDTO.getBusinessType());
        String corpid = userTeamBatchAddDTO.getCorpid();
        Long dataId = userTeamBatchAddDTO.getDataId();
        Boolean isCustomerNew = userTeamBatchAddDTO.getIsCustomerNew() == null ? false : userTeamBatchAddDTO.getIsCustomerNew();
        UserTeamRealBatchAddDTO realBatchAddDTO = new UserTeamRealBatchAddDTO();
        BeanUtil.copyProperties(userTeamBatchAddDTO,realBatchAddDTO);
        // 自身团队得添加
        if (Objects.equals(userTeamEnum, UserTeamEnum.UNKNOW)) {
            throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        addUserTeam(realBatchAddDTO);
        if (!isCustomerNew) {
            Runnable runnable = () -> {
                try {
                    UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO = new UserTeamBatchAddByOtherBusinessDTO();
                    BeanUtil.copyProperties(userTeamBatchAddDTO, userTeamBatchAddByOtherBusinessDTO);
                    switch (userTeamEnum) {
                        case CUSTOMER_TEAM:
                            // 去除客户标签
                            boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
                            CustomerEntityExt customerEntity = customerModel.getByKey(dataId, corpid);
                            Long customerFormId  = customerEntity != null ? customerEntity.getFormId() : 0L;
                            if (customerSeniorModel){
                                transferBackRuleScriptService.deletePublicSeniorTag(corpid,Collections.singletonList(dataId),XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),customerFormId);
                            }else {
                                customerRuleService.deletePublicTag(corpid, Collections.singletonList(dataId));
                            }
                            // 联系人
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(ContactEnum.CUSTOMER_NAME.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 合同
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(ContractEnum.LINK_CUSTOMER.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 退货退款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.REFUND.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(RefundEnum.CUSTOMER_ID.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 应收款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PaymentEnum.CUSTOMER.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 机会
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(SalesOpportunityEnum.CUSTOMER_NAME.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 报价单
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.QUOTATION.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(QuotationEnum.CUSTOMER_ID.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 预收款余额
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PaymentBalanceEnum.CUSTOMER_ID.getAttr());
                            batchAddOtherBusinessUserTeamByCustomerId(userTeamBatchAddByOtherBusinessDTO);
                            break;
                        case CONTRACT_TEAM:
                            // 退货退款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.REFUND.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(RefundEnum.CONTRACT_ID.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 应收款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PaymentEnum.CONTRACT.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            break;
                        case SUPPLIER_TEAM:
                            // 联系人
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(SupplierContactEnum.SUPPLIER_ID.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            // 预付款余额
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PREPAY_BALANCE.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PayBalanceEnum.SUPPLIER_ID.getAttr());
                            batchAddOtherBusinessUserTeamBySupplierId(userTeamBatchAddByOtherBusinessDTO);
                            break;
                        case PURCHASE_TEAM:
                            // 付款计划
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PayPlanEnum.LINK_PURCHASE.getAttr());
                            batchAddUserTeamByOtherBusiness(userTeamBatchAddByOtherBusinessDTO);
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                    LOG.error("com.xbongbong.saas.service.impl.UserTeamServiceImpl.batchAddMainUser", e);
                }
            };
            threadPoolBeanConfig.batchAddOrDelTeam().execute(runnable);
        }
    }
    /**
     * 添加团队人员
     *
     * @param userTeamRealBatchAddDTO
     * @throws XbbException
     */
    private void addUserTeam(UserTeamRealBatchAddDTO userTeamRealBatchAddDTO) throws XbbException {
        String corpid = userTeamRealBatchAddDTO.getCorpid();
        List<String> userIdIn = userTeamRealBatchAddDTO.getUserIdIn();
        Integer businessType = userTeamRealBatchAddDTO.getBusinessType();
        Long dataId = userTeamRealBatchAddDTO.getDataId();
        Integer isMain = userTeamRealBatchAddDTO.getIsMain();

        // 去掉空字符串
        if(Objects.isNull(userIdIn) || userIdIn.isEmpty()) {
            return;
        }
        userIdIn.removeIf(userId -> StringUtil.isEmpty(userId));
        if(userIdIn.isEmpty()) {
            return;
        }

        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userEntityList.forEach(userEntity -> userMap.put(userEntity.getUserId(), userEntity));
        List<UserTeamEntity> userTeamEntityList = new ArrayList<>();
        for (String userId : userIdIn) {
                UserEntity userEntity = userMap.get(userId);
                if (Objects.isNull(userEntity)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100127);
                }
                UserTeamEntity userTeamEntity = new UserTeamEntity();
                initEntity(userTeamEntity,userEntity);
                userTeamEntity.setIsMain(isMain);
                userTeamEntity.setDataId(dataId);
                userTeamEntityList.add(userTeamEntity);
        }
        if (CollectionsUtil.isNotEmpty(userTeamEntityList)) {
            Boolean isCustomerNew = userTeamRealBatchAddDTO.getIsCustomerNew();
            insertBatchUserTeam(corpid, userEntityList, dataId, businessType, userTeamEntityList, isCustomerNew);
        }
    }

    private void insertBatchUserTeam(String corpid, List<UserEntity> userEntities, Long dataId, Integer businessType, List<UserTeamEntity> userTeamEntityList) throws XbbException {
        insertBatchUserTeam(corpid, userEntities, dataId, businessType, userTeamEntityList, false);
    }
    private void insertBatchUserTeam(String corpid, List<UserEntity> userEntities, Long dataId, Integer businessType, List<UserTeamEntity> userTeamEntityList, Boolean isCustomerNew) throws XbbException {
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                List<CustomerUserEntity> customerUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, customerUserEntityList, CustomerUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                if (!customerUserEntityList.isEmpty()) {
                    if (customerUserEntityList.size() == 1) {
                        customerUserModel.insert(customerUserEntityList.get(0));
                    } else {
                        customerUserModel.insertBatch(customerUserEntityList, true);
                    }
                }

                if (Objects.isNull(isCustomerNew)) {
                    isCustomerNew = false;
                }
                if (!isCustomerNew) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(CustomerManagementEnum.DISTRIBUTION_DATE.getAttr(),DateTimeUtil.getInt());
                    UpdateDataEntity updateData = ExplainUtil.getUpdateData(dataId, jsonObject, corpid);
                    customerModel.updateBatch(Collections.singletonList(updateData), corpid);
//                    //评分更新（插入团队，修改了更新时间）分配时间不参与评分
//                    if(Objects.isNull(updateData)){
//                        scoreCalculateService.asyncUpdateSingleDataScore(XbbRefTypeEnum.CUSTOMER_MANAGEMENT,corpid,dataId,null);
//                    }
                }
                if (CollectionsUtil.isNotEmpty(userTeamEntityList) && Objects.equals(userTeamEntityList.get(0).getIsMain(), BasicConstant.MAIN_USER) && !isCustomerNew) {
                    for (UserEntity userEntity : userEntities) {
                        customerRuleService.updateGainRateToRedis(corpid,userEntity);
                    }
                }
                break;
            case CONTACT_TEAM:
                List<ContactUserEntity> contactUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, contactUserEntityList, ContactUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                // 联系人团队插入客户id不可为null
                PaasFormDataEntityExt contactEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(contactEntity)) {
                    Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(contactEntity.getData(), ContactEnum.CUSTOMER_NAME.getAttr(), 0L);
                    for (ContactUserEntity contactUserEntity : contactUserEntityList) {
                        contactUserEntity.setCustomerId(customerId);
                    }
                    // 更新时间
                    contactModel.updateTime(contactEntity.getId(),corpid);
                    contactUserModel.insertBatch(contactUserEntityList, false);
                }

                break;
            case SUPPLIER_CONTACT_TEAM:
                List<SupplierContactUserEntity> supplierContactUserEntities = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, supplierContactUserEntities, SupplierContactUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt supplierContactEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(supplierContactEntity)) {
                    Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(supplierContactEntity.getData(), SupplierContactEnum.SUPPLIER_ID.getAttr(), 0L);
                    for (SupplierContactUserEntity supplierContactUserEntity : supplierContactUserEntities) {
                        supplierContactUserEntity.setSupplierId(supplierId);
                    }
                    // 更新时间
                    supplierContactModel.updateTime(supplierContactEntity.getId(),corpid);
                    supplierContactUserModel.insetBatch(supplierContactUserEntities);
                }
                break;
            case OPPORTUNITY_TEAM:
                List<OpportunityUserEntity> opportunityUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, opportunityUserEntityList, OpportunityUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt opportunityEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(opportunityEntity)) {
                    Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(opportunityEntity.getData(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), 0L);
                    for (OpportunityUserEntity entity : opportunityUserEntityList){
                        entity.setCustomerId(customerId);
                    }
                    // 更新时间
                    opportunityModel.updateTime(opportunityEntity.getId(),corpid);
                }
                opportunityUserModel.insertBatch(opportunityUserEntityList, false);
                break;
            case CONTRACT_TEAM:
                List<ContractUserEntity> contractUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, contractUserEntityList, ContractUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt contractEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(contractEntity)){
                    Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(contractEntity.getData(), ContractEnum.LINK_CUSTOMER.getAttr(), 0L);
                    for (ContractUserEntity entity : contractUserEntityList){
                        entity.setCustomerId(customerId);
                    }
                    // 更新时间
                    contractModel.updateTime(contractEntity.getId(),corpid);
                }
                contractUserModel.insertBatch(contractUserEntityList, false);
                break;
            case QUOTATION_TEAM:
                List<QuotationUserEntity> quotationUserEntities = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, quotationUserEntities, QuotationUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt quotationEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(quotationEntity)){
                    Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(quotationEntity.getData(), QuotationEnum.CUSTOMER_ID.getAttr(), 0L);
                    for (QuotationUserEntity entity : quotationUserEntities){
                        entity.setCustomerId(customerId);
                    }
                    // 更新时间
                    quotationModel.updateTime(quotationEntity.getId(),corpid);
                }
                quotationUserModel.insertBatch(quotationUserEntities, false);
                break;
            case PAYMENT_TEAM:
                List<PaymentUserEntity> paymentUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, paymentUserEntityList, PaymentUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                // 回款团队插入合同id不可为null
                PaasFormDataEntityExt paymentEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(paymentEntity)) {
                    for (PaymentUserEntity paymentUserEntity : paymentUserEntityList) {
                        paymentUserEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(paymentEntity.getData(), PaymentEnum.CUSTOMER.getAttr(), 0L));
                        paymentUserEntity.setContractId(FastJsonHelper.getLongOrDefaultFromFormData(paymentEntity.getData(), PaymentEnum.CONTRACT.getAttr(), 0L));
                    }
                    // 更新时间
                    paymentModel.updateTime(paymentEntity.getId(),corpid);
                    paymentUserModel.insertBatch(paymentUserEntityList);
                }
                break;
            case PAY_PLAN_TEAM:
                List<PayPlanUserEntity> payPlanUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, payPlanUserEntityList, PayPlanUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                // 付款团队插入采购合同id不可为null
                PaasFormDataEntityExt payPlanEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(payPlanEntity)) {
                    for (PayPlanUserEntity payPlanUserEntity : payPlanUserEntityList) {
                        payPlanUserEntity.setSupplierId(FastJsonHelper.getLongOrDefaultFromFormData(payPlanEntity.getData(), PayPlanEnum.LINK_SUPPLIER.getAttr(), 0L));
                        payPlanUserEntity.setPurchaseId(FastJsonHelper.getLongOrDefaultFromFormData(payPlanEntity.getData(), PayPlanEnum.LINK_PURCHASE.getAttr(), 0L));
                    }
                    // 更新时间
                    payPlanModel.updateTime(payPlanEntity.getId(),corpid);
                    payPlanUserModel.insertBatch(payPlanUserEntityList);
                }
                break;
            case REFUND_TEAM:
                List<RefundUserEntity> refundUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, refundUserEntityList, RefundUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                // 退货退款需要合同id
                PaasFormDataEntityExt refundEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(refundEntity)) {
                    for (RefundUserEntity refundUserEntity : refundUserEntityList) {
                        refundUserEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(refundEntity.getData(), RefundEnum.CUSTOMER_ID.getAttr(), 0L));
                        refundUserEntity.setContractId(FastJsonHelper.getLongOrDefaultFromFormData(refundEntity.getData(), RefundEnum.CONTRACT_ID.getAttr(), 0L));
                    }
                    refundModel.updateTime(refundEntity.getId(),corpid);
                }
                refundUserModel.insertBatch(refundUserEntityList, false);
                break;
            case SUPPLIER_TEAM:
                List<SupplierUserEntity> supplierUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, supplierUserEntityList, SupplierUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt supplierEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(supplierEntity)) {
                    supplierModel.updateTime(supplierEntity.getId(),corpid);
                }
                supplierUserModel.insertBatch(supplierUserEntityList, false);
                break;
            case PURCHASE_TEAM:
                List<PurchaseUserEntity> purchaseUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, purchaseUserEntityList, PurchaseUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt purchaseEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(purchaseEntity)) {
                    purchaseModel.updateTime(purchaseEntity.getId(),corpid);
                }
                purchaseUserModel.insertBatch(purchaseUserEntityList, false);
                break;
            case BOMBILL_TEAM:
                List<BomUserEntity> bomUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, bomUserEntityList, BomUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt bomBillEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(bomBillEntity)) {
                    bomBillModel.updateTime(bomBillEntity.getId(),corpid);
                }
                bomUserModel.insertBatch(bomUserEntityList, false);
                break;
            case PRODUCTIONORDER_TEAM:
                List<ProductionOrderUserEntity> productionOrderUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, productionOrderUserEntityList, ProductionOrderUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt productionOrderEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(productionOrderEntity)) {
                    productionOrderModel.updateTime(productionOrderEntity.getId(),corpid);
                }
                productionOrderUserModel.insertBatch(productionOrderUserEntityList, false);
                break;
            case WORK_ORDER_TEAM:
                List<WorkOrderFlowUserEntity> workOrderFlowUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, workOrderFlowUserEntityList, WorkOrderFlowUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt workOrderEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(workOrderEntity)) {
                    workOrderModel.updateTime(workOrderEntity.getId(),corpid);
                }
                workOrderFlowUserModel.insertBatch(workOrderFlowUserEntityList);
                break;
            case PAYMENT_BALANCE_TEAM:
                List<PaymentBalanceUserEntity> paymentBalanceUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, paymentBalanceUserEntityList, PaymentBalanceUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt paymentBalanceEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(paymentBalanceEntity)) {
                    paymentBalanceModel.updateTime(paymentBalanceEntity.getId(),corpid);
                }
                paymentBalanceUserModel.insertBatch(paymentBalanceUserEntityList);
                break;
            case PAY_BALANCE_TEAM:
                List<PayBalanceUserEntity> payBalanceUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, payBalanceUserEntityList, PayBalanceUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt payBalanceEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(payBalanceEntity)) {
                    payBalanceModel.updateTime(payBalanceEntity.getId(),corpid);
                }
                payBalanceUserModel.insertBatch(payBalanceUserEntityList);
                break;
            case CLUE_TEAM:
                List<ClueUserEntity> clueUserEntities = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, clueUserEntities, ClueUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt clueEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(clueEntity)) {
                    clueModel.updateTime(clueEntity.getId(),corpid);
                }
                clueUserModel.insertBatch(clueUserEntities);
                break;
            case MARKET_ACTIVITY_TEAM:
                List<MarketActivityUserEntity> marketActivityUserEntities = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, marketActivityUserEntities, MarketActivityUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                PaasFormDataEntityExt marketActivityEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if (Objects.nonNull(marketActivityEntity)) {
                    marketActivityModel.updateTime(marketActivityEntity.getId(),corpid);
                }
                marketActivityUserModel.insertBatch(marketActivityUserEntities,false);
                break;
            case WAREHOUSE_TEAM:
                List<WarehouseUserEntity> warehouseUserEntityList = warehouseTeamTransferSubForm.transferUserTeamUserToWarehouseUser(userTeamEntityList);
                PaasFormDataEntityExt warehouseEntity = proGetHelp.getByKey(dataId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if(Objects.nonNull(warehouseEntity)){
                    WarehouseEntityExt warehouseEntityExt = new WarehouseEntityExt();
                    JSONObject originData = warehouseEntity.getData();
                    JSONArray mainUserArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(originData,WarehouseEnum.MANAGER_ID.getAttr(), new JSONArray());
                    warehouseUserEntityList.forEach(item -> {
                        mainUserArray.add(item.getRelationId());
                    });
                    BeanUtil.copyProperties(warehouseEntity,warehouseEntityExt);
                    warehouseModel.update(warehouseEntityExt);
                }
                warehouseUserModel.insertBatch(warehouseUserEntityList,false);
                break;
            default:
                break;

        }
    }

    /**
     * 添加团队人员
     *
     * @param corpid 公司id
     * @param userIdIn 用户
     * @param dataIdIn 数据id
     * @param isMain 负责协同
     * @throws XbbException
     */
    private void addUserTeam(String corpid, List<String> userIdIn, List<Long> dataIdIn, Integer isMain, Integer businessType) throws XbbException {
        Map<String, String> errorMsgMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userEntityList.forEach(userEntity -> userMap.put(userEntity.getUserId(), userEntity));
        for (Long dataId : dataIdIn) {
            List<UserTeamEntity> userTeamEntityList = new ArrayList<>();
            for (String userId : userIdIn) {
                UserEntity userEntity = userMap.get(userId);
                if (Objects.isNull(userEntity)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100065);
                }
                UserTeamEntity userTeamEntity = new UserTeamEntity();
                initEntity(userTeamEntity, userEntity);
                userTeamEntity.setIsMain(isMain);
                userTeamEntity.setDataId(dataId);
                userTeamEntityList.add(userTeamEntity);
            }
            insertBatchUserTeam(corpid, userEntityList, dataId, businessType, userTeamEntityList);
        }

    }

    private void addWorkOrderUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("dataId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<WorkOrderFlowUserEntity> workOrderFlowUserEntities = workOrderFlowUserModel.findEntitys(param);

        if (workOrderFlowUserEntities.size() > BasicConstant.ZERO) {
            for (WorkOrderFlowUserEntity flowUserEntity : workOrderFlowUserEntities) {
                if (!Objects.equals(flowUserEntity.getIsMain(), isMain) && !Objects.equals(flowUserEntity.getIsMain(), BasicConstant.ONE)) {
                    flowUserEntity.setIsMain(isMain);
                    workOrderFlowUserModel.save(flowUserEntity);
                }
            }
        } else {
            UserEntity userEntity = userModel.getByKey(userId, corpid);
            WorkOrderFlowUserEntity workOrderFlowUserEntity = new WorkOrderFlowUserEntity();
            initEntity(workOrderFlowUserEntity, userEntity);
            workOrderFlowUserEntity.setDataId(dataId);
            if (isMain == null) {
                workOrderFlowUserEntity.setIsMain(MAIN_USER);
            }
            workOrderFlowUserEntity.setIsMain(isMain);
            workOrderFlowUserModel.save(workOrderFlowUserEntity);
        }
    }

    private void addContactUserBySupplierId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.SUPPLIER_CONTACT.getCode(), SupplierContactEnum.SUPPLIER_ID.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
        List<Long> contactIds = new ArrayList<>();
        contactIds.add(-1L);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> contactIds.add(paasFormDataEntityExt.getId())));
        param.put("contactIdIn", contactIds);
        param.put(ParameterConstant.USER_ID, userId);
        param.put("del",0);
        List<SupplierContactUserEntity> withContactUserTeamList = supplierContactUserModel.findEntitys(param);
        if (withContactUserTeamList.size() > BasicConstant.ZERO) {
            for (SupplierContactUserEntity contactUserEntity : withContactUserTeamList) {
                if (!Objects.equals(contactUserEntity.getIsMain(), isMain) && !Objects.equals(contactUserEntity.getIsMain(), BasicConstant.ONE)) {
                    contactUserEntity.setIsMain(isMain);
                    supplierContactUserModel.save(contactUserEntity);
                }
            }
        } else {
            for (Long contactId : contactIds) {
                createSupplierContactUser(corpid, userId, dataId, contactId, isMain);
            }
        }
    }

    private void createSupplierContactUser(String corpid, String userId, Long dataId, Long contactId, Integer isMain) throws XbbException{
        if (contactId < 0){
            return;
        }
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        SupplierContactUserEntity contactUserEntity = new SupplierContactUserEntity();
        initEntity(contactUserEntity, userEntity);
        contactUserEntity.setSupplierId(dataId);
        contactUserEntity.setDataId(contactId);
        contactUserEntity.setIsMain(isMain);
        supplierContactUserModel.save(contactUserEntity);
    }
    /**
     * 根据退货退款id添加退货退款负责团队
     * 用于合同详情添加负责人，不会有新团队创建
     * @param corpid 公司id
     * @param userId 添加人
     * @param dataId 合同id
     * @param isMain 主负责人
     * @throws XbbException
     */
    private void addRefundUserByRefundId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("refundId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<RefundUserEntity> refundUserTeamList = refundUserModel.findEntitys(param);
        if (refundUserTeamList.size() > BasicConstant.ZERO) {
            for (RefundUserEntity refundUserEntity : refundUserTeamList) {
                if (!Objects.equals(refundUserEntity.getIsMain(), isMain) && !Objects.equals(refundUserEntity.getIsMain(), BasicConstant.ONE)) {
                    refundUserEntity.setIsMain(isMain);
                    refundUserModel.save(refundUserEntity);
                }
            }
        } else {
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            RefundUserEntity refundUserEntity = new RefundUserEntity();
            initEntity(refundUserEntity, userEntity);
            PaasFormDataEntityExt paasFormDataEntityExt = proGetHelp.getByKey(dataId, RedundantTemplateTypeEnum.REFUND.getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
            Long contractId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), RefundEnum.RED_CONTRACT_ID.getAttr(), 0L);
            refundUserEntity.setDataId(dataId);
            refundUserEntity.setContractId(contractId);
            refundUserEntity.setIsMain(isMain);
            refundUserModel.save(refundUserEntity);
        }
    }



    private void addContactUserByCustomerId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.CONTACT.getCode(), ContactEnum.CUSTOMER_NAME.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_CONTACT);
        List<Long> contactIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> contactIds.add(paasFormDataEntityExt.getId())));
        if (contactIds.isEmpty()) {
            contactIds.add(-1L);
        }
        param.put("contactIdIn", contactIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<ContactUserEntity> withContactUserTeamList = contactUserModel.findEntitys(param);
        if (withContactUserTeamList.size() > BasicConstant.ZERO) {
            for (ContactUserEntity contactUserEntity : withContactUserTeamList) {
                if (!Objects.equals(contactUserEntity.getIsMain(), isMain) && !Objects.equals(contactUserEntity.getIsMain(), BasicConstant.ONE)) {
                    contactUserEntity.setIsMain(isMain);
                    contactUserModel.save(contactUserEntity);
                }
            }
        } else {
            // 防止 -1 作为值插入数据库
            contactIds.remove(-1L);
            for (Long contactId : contactIds) {
                createContactUser(corpid, userId, dataId, contactId, isMain);
            }
        }
    }

    private void batchAddUserTeamByOtherBusiness(UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO) throws XbbException{
        String corpid = userTeamBatchAddByOtherBusinessDTO.getCorpid();
        String relyAttr = userTeamBatchAddByOtherBusinessDTO.getRelyAttr();
        Long dataId = userTeamBatchAddByOtherBusinessDTO.getDataId();
        Integer businessType = userTeamBatchAddByOtherBusinessDTO.getBusinessType();
        List<String> userIdIn = userTeamBatchAddByOtherBusinessDTO.getUserIdIn();
        if (CollectionsUtil.isEmpty(userIdIn)) {
            return;
        }
        Integer isMain = userTeamBatchAddByOtherBusinessDTO.getIsMain();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        if(Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),businessType) || Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(),businessType)){
            boolQueryBuilder.filter(termQuery(relyAttr + ".keyword", dataId.toString()));
        }else {
            boolQueryBuilder.filter(termQuery("data."+ relyAttr + ".keyword", dataId.toString()));
        }
        List<String> fieldList = new ArrayList<>();
        fieldList.add(FieldTypeEnum.DATAID.getAlias());

        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        List<PaasFormDataEntityExt> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        List<Long> otherBusinessIdIn = new ArrayList<>();
        paasFormDataList.forEach(paasFormDataEntityExt -> otherBusinessIdIn.add(paasFormDataEntityExt.getDataId()));
        if (otherBusinessIdIn.isEmpty()) {
            return;
        }
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, businessType);
        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, ParameterConstant.USER_ID), userIdIn));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, StringConstant.DATA_ID) , otherBusinessIdIn));

        List<PaasFormDataEntity> teamEntityList = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, teamEntityList);
        Map<String, UserTeamEntity> teamMap = new HashMap<>(DEFAULT_INITIAL_CAPACITY);
        teamList.forEach(userTeamEntity -> teamMap.put(userTeamEntity.getDataId() + StringConstant.COMMA + userTeamEntity.getUserId(), userTeamEntity));
        Map<Long, List<UserTeamEntity>> existUserIdInTeamMap = new HashMap<>(DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<UserTeamEntity>> updateIsMainUserIdInMap = new HashMap<>(DEFAULT_INITIAL_CAPACITY);
        String key;
        List<UserTeamEntity> userTeamEntityList;
        for (Long otherId : otherBusinessIdIn) {
            for (String userId : userIdIn) {
                 key = otherId + StringConstant.COMMA + userId;
                 if (teamMap.containsKey(key)) {
                     UserTeamEntity userTeamEntity = teamMap.get(key);
                     if (Objects.equals(userTeamEntity.getIsMain(), isMain)) {
                         userTeamEntityList = new ArrayList<>();
                         if (existUserIdInTeamMap.containsKey(otherId)) {
                             userTeamEntityList = existUserIdInTeamMap.get(otherId);
                         }
                         userTeamEntityList.add(userTeamEntity);
                         existUserIdInTeamMap.put(otherId, userTeamEntityList);
                     } else {
                         userTeamEntityList = new ArrayList<>();
                         if (updateIsMainUserIdInMap.containsKey(otherId)) {
                             userTeamEntityList = updateIsMainUserIdInMap.get(otherId);
                         }
                         userTeamEntityList.add(userTeamEntity);
                         updateIsMainUserIdInMap.put(otherId, userTeamEntityList);
                     }
                 }
            }
        }
        List<UserTeamEntity> userTeamList;
        List<String> copyUserIdIn = (List<String>)CloneUtil.deepClone(userIdIn);
        // 客户合并副客户下游业务没有主客户的负责团队
        List<Long> mergeBusinessIdIn = new ArrayList<>();
        if (!existUserIdInTeamMap.isEmpty() || !updateIsMainUserIdInMap.isEmpty()) {
            for (Long otherId : otherBusinessIdIn) {
                if (existUserIdInTeamMap.containsKey(otherId)) {
                    userTeamList = existUserIdInTeamMap.get(otherId);
                    List<String> existUserIds = new ArrayList<>();
                    userTeamList.forEach(userTeam-> existUserIds.add(userTeam.getUserId()));
                    copyUserIdIn.removeIf(userId-> existUserIds.contains(userId));
                }
                if (updateIsMainUserIdInMap.containsKey(otherId)) {
                    userTeamList = updateIsMainUserIdInMap.get(otherId);
                    List<String> updateUserIds = new ArrayList<>();
                    userTeamList.forEach(userTeam-> updateUserIds.add(userTeam.getUserId()));
                    copyUserIdIn.removeIf(userId-> updateUserIds.contains(userId));
                    UserTeamBatchUpdateDTO userTeamBatchUpdateDTO = new UserTeamBatchUpdateDTO();
                    BeanUtil.copyProperties(userTeamBatchAddByOtherBusinessDTO, userTeamBatchUpdateDTO);
                    userTeamBatchUpdateDTO.setBusinessType(businessType);
                    userTeamBatchUpdateDTO.setIsMain(isMain);
                    userTeamBatchUpdateDTO.setOtherId(otherId);
                    userTeamBatchUpdateDTO.setUpdateUserIdIn(updateUserIds);
                    batchUpdateUserTeam(userTeamBatchUpdateDTO);
                }
                if (!copyUserIdIn.isEmpty()) {
                    UserTeamRealBatchAddDTO userTeamRealBatchAddDTO = new UserTeamRealBatchAddDTO();
                    BeanUtil.copyProperties(userTeamBatchAddByOtherBusinessDTO, userTeamRealBatchAddDTO);
                    userTeamRealBatchAddDTO.setDataId(otherId);
                    userTeamRealBatchAddDTO.setUserIdIn(copyUserIdIn);
                    addUserTeam(userTeamRealBatchAddDTO);
                }
                // 记录客户合并副客户下游业务没有主客户的负责团队 -》这样的对应业务dataId
                if (!existUserIdInTeamMap.containsKey(otherId) && !updateIsMainUserIdInMap.containsKey(otherId) && copyUserIdIn.isEmpty()){
                    mergeBusinessIdIn.add(otherId);
                }
            }

        } else {
            if (!userIdIn.isEmpty()) {
                addUserTeam(corpid, userIdIn, otherBusinessIdIn, isMain, businessType);
            }
        }
        // 更新一下这类业务的id
        if ((!existUserIdInTeamMap.isEmpty() || !updateIsMainUserIdInMap.isEmpty()) && !mergeBusinessIdIn.isEmpty()){
            addUserTeam(corpid, userIdIn, mergeBusinessIdIn, isMain, businessType);
        }

    }

    /**
     * 关联更新其他业务的团队
     * @param userTeamBatchAddByOtherBusinessDTO
     * @throws XbbException
     */
    private void batchAddOtherBusinessUserTeamByCustomerId(UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO) throws XbbException{
        String corpid = userTeamBatchAddByOtherBusinessDTO.getCorpid();
        String relyAttr = userTeamBatchAddByOtherBusinessDTO.getRelyAttr();
        Long customerId = userTeamBatchAddByOtherBusinessDTO.getDataId();
        Integer businessType = userTeamBatchAddByOtherBusinessDTO.getBusinessType();
        List<String> userIdIn = userTeamBatchAddByOtherBusinessDTO.getUserIdIn();
        if (CollectionsUtil.isEmpty(userIdIn)) {
            return;
        }
        Integer isMain = userTeamBatchAddByOtherBusinessDTO.getIsMain();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, businessType);
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(PaymentBalanceTeamEnum.getAttrConnectData(PaymentBalanceTeamEnum.USER_ID), userIdIn));
        //关联字段
        boolQueryBuilder.filter(termQuery(relyAttr , customerId));

        List<PaasFormDataEntity> balanceUserLists = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<PaymentBalanceUserEntity> teamList = (List<PaymentBalanceUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, balanceUserLists);
        //新加的团队原来没有
        if(!teamList.isEmpty()){
            Map<String, PaymentBalanceUserEntity> teamMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            teamList.forEach(paymentBalanceUserEntity -> teamMap.put(paymentBalanceUserEntity.getUserId(), paymentBalanceUserEntity));
            //不同的user对于同一个客户只会存在异常，所以此只存userId即可
            Set<String>  existUserIdSet = new HashSet<>();
            //存在需要更新isMain
            Set<String>  updateIsMainUserIdSet = new HashSet<>();
            List<PaymentBalanceUserEntity> updateList =  new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> updataIdIn = new ArrayList<>();
            for (String userId : userIdIn) {
                if (teamMap.containsKey(userId)) {
                    PaymentBalanceUserEntity paymentBalanceUserEntity = teamMap.get(userId);
                    if (Objects.equals(paymentBalanceUserEntity.getIsMain(), isMain)) {
                        existUserIdSet.add(userId);
                    } else {
                        updateIsMainUserIdSet.add(userId);
                        updateList.add(paymentBalanceUserEntity);
                        updataIdIn.add(paymentBalanceUserEntity.getId());
                    }
                }
            }
            if(!existUserIdSet.isEmpty() || !updateIsMainUserIdSet.isEmpty()){
                List<String> copyUserIdIn = (List<String>)CloneUtil.deepClone(userIdIn);
                //移除存在的
                copyUserIdIn.removeAll(existUserIdSet);
                if( !updateIsMainUserIdSet.isEmpty()){
                    paymentBalanceUserModel.batchUpdateByUserIds(corpid, updataIdIn, updateList, isMain, null);
                    copyUserIdIn.removeAll(updateIsMainUserIdSet);
                }
                if (!copyUserIdIn.isEmpty()) {
                    addUserTeam(corpid, customerId, isMain, copyUserIdIn);
                }
            }else {
                addUserTeam(corpid, customerId, isMain, userIdIn);
            }
        }else{
            addUserTeam(corpid, customerId, isMain, userIdIn);
        }
    }

    /**
     * 关联更新预付款余额的团队
     * @param userTeamBatchAddByOtherBusinessDTO
     * @throws XbbException
     */
    private void batchAddOtherBusinessUserTeamBySupplierId(UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO) throws XbbException{
        String corpid = userTeamBatchAddByOtherBusinessDTO.getCorpid();
        String relyAttr = userTeamBatchAddByOtherBusinessDTO.getRelyAttr();
        Long supplierId = userTeamBatchAddByOtherBusinessDTO.getDataId();
        Integer businessType = userTeamBatchAddByOtherBusinessDTO.getBusinessType();
        List<String> userIdIn = userTeamBatchAddByOtherBusinessDTO.getUserIdIn();
        if (CollectionsUtil.isEmpty(userIdIn)) {
            return;
        }
        Integer isMain = userTeamBatchAddByOtherBusinessDTO.getIsMain();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, businessType);
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(PayBalanceTeamEnum.getAttrConnectData(PayBalanceTeamEnum.USER_ID), userIdIn));
        //关联字段
        boolQueryBuilder.filter(termQuery(relyAttr , supplierId));

        List<PaasFormDataEntity> balanceUserLists = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<PayBalanceUserEntity> teamList = (List<PayBalanceUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, balanceUserLists);
        //新加的团队原来没有
        if(!teamList.isEmpty()){
            Map<String, PayBalanceUserEntity> teamMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            teamList.forEach(entity -> teamMap.put(entity.getUserId(), entity));
            //不同的user对于同一个客户只会存在异常，所以此只存userId即可
            Set<String>  existUserIdSet = new HashSet<>();
            //存在需要更新isMain
            Set<String>  updateIsMainUserIdSet = new HashSet<>();
            List<PayBalanceUserEntity> updateList =  new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> updataIdIn = new ArrayList<>();
            for (String userId : userIdIn) {
                if (teamMap.containsKey(userId)) {
                    PayBalanceUserEntity payBalanceUserEntity = teamMap.get(userId);
                    if (Objects.equals(payBalanceUserEntity.getIsMain(), isMain)) {
                        existUserIdSet.add(userId);
                    } else {
                        updateIsMainUserIdSet.add(userId);
                        updateList.add(payBalanceUserEntity);
                        updataIdIn.add(payBalanceUserEntity.getId());
                    }
                }
            }
            if(!existUserIdSet.isEmpty() || !updateIsMainUserIdSet.isEmpty()){
                List<String> copyUserIdIn = (List<String>)CloneUtil.deepClone(userIdIn);
                //移除存在的
                copyUserIdIn.removeAll(existUserIdSet);
                if( !updateIsMainUserIdSet.isEmpty()){
                    payBalanceUserModel.batchUpdateByUserIds(corpid, updataIdIn, updateList, isMain, null);
                    copyUserIdIn.removeAll(updateIsMainUserIdSet);
                }
                if (!copyUserIdIn.isEmpty()) {
                    addUserTeam4PayBalance(corpid, supplierId, isMain, copyUserIdIn);
                }
            }else {
                addUserTeam4PayBalance(corpid, supplierId, isMain, userIdIn);
            }
        }else{
            addUserTeam4PayBalance(corpid, supplierId, isMain, userIdIn);
        }
    }

    private void addUserTeam(String corpid, Long customerId, Integer isMain, List<String> copyUserIdIn) throws XbbException {
        PaymentBalanceEntity paymentBalanceEntity = paymentBalanceModel.getByCustomerId(customerId,corpid);
        if(paymentBalanceEntity == null){
            return;
        }
        Long id = paymentBalanceEntity.getId();
        List<PaymentBalanceUserEntity> paymentBalanceUserEntityList = new ArrayList<>();
        Map<String, String> userIdNameMap =  userModel.getUserIdNameMap(corpid,copyUserIdIn);
        for (String userId : copyUserIdIn) {
            PaymentBalanceUserEntity paymentBalanceUserEntity = new PaymentBalanceUserEntity(customerId,corpid,userId,userIdNameMap.get(userId),"",id,isMain,0);
            paymentBalanceUserEntityList.add(paymentBalanceUserEntity);
        }
        paymentBalanceUserModel.insertBatch(paymentBalanceUserEntityList);
    }

    /**
     * 增加预付款余额团队
     * @param corpid
     * @param supplierId
     * @param isMain
     * @param copyUserIdIn
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void addUserTeam4PayBalance(String corpid, Long supplierId, Integer isMain, List<String> copyUserIdIn) throws XbbException {
        PayBalanceEntity payBalanceEntity = payBalanceModel.getBySupplierId(supplierId,corpid);
        if(payBalanceEntity == null){
            return;
        }
        Long id = payBalanceEntity.getId();
        List<PayBalanceUserEntity> payBalanceUserEntityList = new ArrayList<>();
        Map<String, String> userIdNameMap =  userModel.getUserIdNameMap(corpid,copyUserIdIn);
        for (String userId : copyUserIdIn) {
            PayBalanceUserEntity payBalanceUserEntity = new PayBalanceUserEntity(supplierId,corpid,userId,userIdNameMap.get(userId),"",id,isMain,0);
            payBalanceUserEntityList.add(payBalanceUserEntity);
        }
        payBalanceUserModel.insertBatch(payBalanceUserEntityList);
    }

    private void batchUpdateUserTeamByOtherBusiness(String corpid, List<String> updateUserIdIn, Long otherId, Integer isMain, Integer businessType, String relyAttr) throws XbbException {
        if (CollectionsUtil.isEmpty(updateUserIdIn)) {
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolean balance = Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), businessType);
        boolean payBalance = Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(), businessType);
        List<String> fieldList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        List<Long> otherBusinessIdIn = new ArrayList<>();
        if(balance){
            boolQueryBuilder.filter(termQuery(relyAttr, otherId));
            fieldList.add("id");
            List<PaymentBalanceEntity> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaymentBalanceEntity.class, fieldList);
            paasFormDataList.forEach(paasFormDataEntityExt -> otherBusinessIdIn.add(paasFormDataEntityExt.getId()));
        } else if (payBalance) {
            boolQueryBuilder.filter(termQuery(relyAttr, otherId));
            fieldList.add("id");
            List<PayBalanceEntity> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PayBalanceEntity.class, fieldList);
            paasFormDataList.forEach(paasFormDataEntityExt -> otherBusinessIdIn.add(paasFormDataEntityExt.getId()));
        }else {
            boolQueryBuilder.filter(termQuery("data."+ relyAttr + ".keyword", otherId.toString()));
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            paasFormDataList.forEach(paasFormDataEntityExt -> otherBusinessIdIn.add(paasFormDataEntityExt.getDataId()));
        }
        if (otherBusinessIdIn.isEmpty()) {
            return;
        }
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, businessType);
        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, ParameterConstant.USER_ID), updateUserIdIn));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, StringConstant.DATA_ID) , otherBusinessIdIn));
        List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, userTeamList);

        List<Long> dataIdIn = new ArrayList<>();
        teamEntityList.forEach(team -> dataIdIn.add(team.getId()));
        if (dataIdIn.isEmpty()) {
            return;
        }
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                customerUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case CONTRACT_TEAM:
                contractUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case QUOTATION_TEAM:
                quotationUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case OPPORTUNITY_TEAM:
                opportunityUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case REFUND_TEAM:
                refundUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case CONTACT_TEAM:
                contactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case SUPPLIER_TEAM:
                supplierUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case SUPPLIER_CONTACT_TEAM:
                supplierContactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case BOMBILL_TEAM:
                bomUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PRODUCTIONORDER_TEAM:
                productionOrderUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PURCHASE_TEAM:
                purchaseUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAYMENT_TEAM:
                paymentUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAYMENT_BALANCE_TEAM:
                paymentBalanceUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            default:
                break;
        }
    }

    private void batchUpdateUserTeam(UserTeamBatchUpdateDTO userTeamBatchUpdateDTO) throws XbbException {
        Integer businessType = userTeamBatchUpdateDTO.getBusinessType();
        String corpid = userTeamBatchUpdateDTO.getCorpid();
        List<String> updateUserIdIn = userTeamBatchUpdateDTO.getUpdateUserIdIn();
        Long otherId = userTeamBatchUpdateDTO.getOtherId();
        Integer isMain = userTeamBatchUpdateDTO.getIsMain();
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, businessType);

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(ParameterConstant.DEL, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel())));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, ParameterConstant.USER_ID), updateUserIdIn));
        boolQueryBuilder.filter(termQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, StringConstant.DATA_ID) , otherId));
        List<PaasFormDataEntity> userTeamList  = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamEntityList = new ArrayList<>();
        if (Objects.equals(businessType,XbbRefTypeEnum.WAREHOUSE.getCode())){
            //仓库的团队表es没有，所以从数据库里面拿
            List<WarehouseUserEntity> warehouseUserEntityList = warehouseUserModel.getUserListByTypeAndDataIdIn(corpid,BasicConstant.ZERO,Arrays.asList(otherId),updateUserIdIn);
            teamEntityList = warehouseTeamTransferSubForm.transferWarehouseUserToUserTeam(warehouseUserEntityList);
        }else {
            teamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, userTeamList);
        }
        List<Long> dataIdIn = new ArrayList<>();
        teamEntityList.forEach(team -> dataIdIn.add(team.getId()));
        if (dataIdIn.isEmpty()) {
            return;
        }
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                customerUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, 0);
                Runnable runnable = () -> {
                    try {
                        batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.CONTACT.getCode(), ContactEnum.CUSTOMER_NAME.getAttr());
                        batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr());
                        batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.CONTRACT.getCode(), ContractEnum.LINK_CUSTOMER.getAttr());
                        batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.REFUND.getCode(), RefundEnum.CUSTOMER_ID.getAttr());
                        batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.PAYMENT.getCode(), PaymentEnum.CUSTOMER.getAttr());
                        batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.QUOTATION.getCode(), QuotationEnum.CUSTOMER_ID.getAttr());
                        batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), PaymentBalanceEnum.CUSTOMER_ID.getAttr());
                    } catch (XbbException e) {
                        LOG.error("com.xbongbong.saas.service.impl.UserTeamServiceImpl.batchUpdateUserTeam", e);
                    }
                };

                threadPoolBeanConfig.batchAddOrDelTeam().execute(runnable);
                break;
            case CONTRACT_TEAM:
                contractUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.REFUND.getCode(), RefundEnum.CONTRACT_ID.getAttr());
                batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.PAYMENT.getCode(), PaymentEnum.CONTRACT.getAttr());
                break;
            case OPPORTUNITY_TEAM:
                opportunityUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case REFUND_TEAM:
                refundUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case CONTACT_TEAM:
                contactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case SUPPLIER_TEAM:
                supplierUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), SupplierContactEnum.SUPPLIER_ID.getAttr());
                batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.PREPAY_BALANCE.getCode(), PayBalanceEnum.SUPPLIER_ID.getAttr());
                break;
            case SUPPLIER_CONTACT_TEAM:
                supplierContactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case BOMBILL_TEAM:
                bomUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PRODUCTIONORDER_TEAM:
                productionOrderUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PURCHASE_TEAM:
                purchaseUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                batchUpdateUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, isMain, XbbRefTypeEnum.PAY_PLAN.getCode(), PayPlanEnum.LINK_PURCHASE.getAttr());
                break;
            case WORK_ORDER_TEAM:
                workOrderFlowUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAYMENT_TEAM:
                paymentUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAY_PLAN_TEAM:
                paymentUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case QUOTATION_TEAM:
                quotationUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAYMENT_BALANCE_TEAM:
                paymentBalanceUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAY_BALANCE_TEAM:
                payBalanceUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case CLUE_TEAM:
                clueUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case MARKET_ACTIVITY_TEAM:
                marketActivityUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case WAREHOUSE_TEAM:
                warehouseUserModel.batchUpdateByUserIdIn(corpid, dataIdIn,BasicConstant.ZERO);
                break;
            default:
                break;
        }
    }

    private void batchDeleteUserTeam(UserTeamBatchDeleteDTO userTeamBatchDeleteDTO) throws XbbException {
        String corpid = userTeamBatchDeleteDTO.getCorpid();
        Integer businessType = userTeamBatchDeleteDTO.getBusinessType();
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, businessType);

        Long otherId = userTeamBatchDeleteDTO.getOtherId();
        List<String> updateUserIdIn = userTeamBatchDeleteDTO.getUpdateUserIdIn();
        Integer del = userTeamBatchDeleteDTO.getDel();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, ParameterConstant.USER_ID), updateUserIdIn));
        boolQueryBuilder.filter(termQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, StringConstant.DATA_ID) , otherId));
        List<PaasFormDataEntity> paasFormDataEntities  = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamEntityList = new ArrayList<>();
        if (Objects.equals(businessType,XbbRefTypeEnum.WAREHOUSE.getCode())){
            //仓库的团队表es没有，所以从数据库里面拿
            List<WarehouseUserEntity> warehouseUserEntityList = warehouseUserModel.getUserListByTypeAndDataIdIn(corpid,BasicConstant.ZERO,Arrays.asList(otherId),updateUserIdIn);
            teamEntityList = warehouseTeamTransferSubForm.transferWarehouseUserToUserTeam(warehouseUserEntityList);
        }else {
            teamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, paasFormDataEntities);
        }

        List<Long> dataIdIn = new ArrayList<>();
        teamEntityList.forEach(team -> dataIdIn.add(team.getId()));
        if (dataIdIn.isEmpty()) {
            return;
        }

        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        // 更新时间
        List<UpdateDataEntity> updateDataList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            UpdateDataEntity updateDataEntity = new UpdateDataEntity();
            updateDataEntity.setCorpid(corpid);
            updateDataEntity.setId(userTeamEntity.getDataId());
            updateDataEntity.setUpdateTime(DateTimeUtil.getInt());
            updateDataList.add(updateDataEntity);
        }
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                customerUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                Runnable runnable = () -> {
                    try {
                        customerFocusModel.unFocusByUserIdIn(otherId, corpid, updateUserIdIn);
                        customerModel.updateBatch(updateDataList,corpid);
                        batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.CONTACT.getCode(), del, ContactEnum.CUSTOMER_NAME.getAttr());
                        batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), del, SalesOpportunityEnum.CUSTOMER_NAME.getAttr());
                        batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.CONTRACT.getCode(), del, ContractEnum.LINK_CUSTOMER.getAttr());
                        batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.REFUND.getCode(), del, RefundEnum.CUSTOMER_ID.getAttr());
                        batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.PAYMENT.getCode(), del, PaymentEnum.CUSTOMER.getAttr());
                        batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.QUOTATION.getCode(), del, QuotationEnum.CUSTOMER_ID.getAttr());
                        batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), del, PaymentBalanceEnum.CUSTOMER_ID.getAttr());
                    } catch (XbbException e) {
                        LOG.error("com.xbongbong.saas.service.impl.UserTeamServiceImpl.batchDeleteUserTeam fail", e);
                    }
                };
                threadPoolBeanConfig.batchAddOrDelTeam().execute(runnable);
                break;
            case CONTRACT_TEAM:
                contractModel.updateBatch(updateDataList,corpid);
                contractUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.REFUND.getCode(), del, RefundEnum.CONTRACT_ID.getAttr());
                batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.PAYMENT.getCode(), del, PaymentEnum.CONTRACT.getAttr());
                break;
            case QUOTATION_TEAM:
                quotationModel.updateBatch(updateDataList,corpid);
                quotationUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case OPPORTUNITY_TEAM:
                opportunityModel.updateBatch(updateDataList,corpid);
                opportunityUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case REFUND_TEAM:
                refundModel.updateBatch(updateDataList,corpid);
                refundUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case CONTACT_TEAM:
                contactModel.updateBatch(updateDataList,corpid);
                contactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case SUPPLIER_TEAM:
                supplierModel.updateBatch(updateDataList,corpid);
                supplierUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), del, SupplierContactEnum.SUPPLIER_ID.getAttr());
                batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.PREPAY_BALANCE.getCode(), del, PayBalanceEnum.SUPPLIER_ID.getAttr());
                break;
            case SUPPLIER_CONTACT_TEAM:
                supplierContactModel.updateBatch(updateDataList,corpid);
                supplierContactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case BOMBILL_TEAM:
                bomBillModel.updateBatch(updateDataList,corpid);
                bomUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PRODUCTIONORDER_TEAM:
                productionOrderModel.updateBatch(updateDataList,corpid);
                productionOrderUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PURCHASE_TEAM:
                purchaseModel.updateBatch(updateDataList,corpid);
                purchaseUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                batchDeleteUserTeamByOtherBusiness(corpid, updateUserIdIn, otherId, XbbRefTypeEnum.PAY_PLAN.getCode(), del, PayPlanEnum.LINK_PURCHASE.getAttr());
                break;
            case WORK_ORDER_TEAM:
                workOrderModel.updateBatch(updateDataList,corpid);
                workOrderFlowUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PAYMENT_TEAM:
                paymentModel.updateBatch(updateDataList,corpid);
                paymentUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PAY_PLAN_TEAM:
                paymentModel.updateBatch(updateDataList,corpid);
                paymentUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case CLUE_TEAM:
                clueModel.updateBatch(updateDataList,corpid);
                clueUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case MARKET_ACTIVITY_TEAM:
                marketActivityModel.updateBatch(updateDataList,corpid);
                marketActivityUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case WAREHOUSE_TEAM:
                //仓库团队这边特殊处理，因为仓库的负责人是在主表Data中的，所以团队表和主表都要更新
                PaasFormDataEntityExt warehouseEntity = proGetHelp.getByKey(otherId, businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                if(Objects.nonNull(warehouseEntity)){
                    WarehouseEntityExt warehouseEntityExt = new WarehouseEntityExt();
                    JSONObject originData = warehouseEntity.getData();
                    JSONArray managerIds = FastJsonHelper.getJsonArrOrDefaultFromFormData(originData, WarehouseEnum.MANAGER_ID.getAttr(), new JSONArray());
                    if(CollectionsUtil.isNotEmpty(managerIds)){
                        updateUserIdIn.forEach(userId -> {
                            managerIds.removeIf(item -> Objects.equals(item,userId));
                        });
                        originData.put(WarehouseEnum.MANAGER_ID.getAttr(),managerIds);
                        BeanUtil.copyProperties(warehouseEntity,warehouseEntityExt);
                    }
                    warehouseModel.update(warehouseEntityExt);
                }
                warehouseUserModel.batchUpdateByUserIdIn(corpid,dataIdIn,del);
                break;
            default:
                break;
        }
    }

    private void batchDeleteUserTeamByOtherBusiness(String corpid, List<String> updateUserIdIn, Long otherId,  Integer businessType, Integer del, String relyAttr) throws XbbException {
        if (CollectionsUtil.isEmpty(updateUserIdIn)) {
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        List<String> fieldList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        List<Long> otherBusinessIdIn = new ArrayList<>();
        if(Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),businessType)){
            boolQueryBuilder.filter(termQuery(relyAttr, otherId));
            fieldList.add("id");
            List<PaymentBalanceEntity> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaymentBalanceEntity.class, fieldList);
            paasFormDataList.forEach(paasFormDataEntityExt -> otherBusinessIdIn.add(paasFormDataEntityExt.getId()));
        } else if (Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(),businessType)) {
            boolQueryBuilder.filter(termQuery(relyAttr, otherId));
            fieldList.add("id");
            List<PayBalanceEntity> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PayBalanceEntity.class, fieldList);
            paasFormDataList.forEach(paasFormDataEntityExt -> otherBusinessIdIn.add(paasFormDataEntityExt.getId()));
        }else {
            boolQueryBuilder.filter(termQuery("data."+ relyAttr + ".keyword", otherId.toString()));
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            paasFormDataList.forEach(paasFormDataEntityExt -> otherBusinessIdIn.add(paasFormDataEntityExt.getDataId()));
        }
        if (otherBusinessIdIn.isEmpty()) {
            return;
        }
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, businessType);

        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, ParameterConstant.USER_ID), updateUserIdIn));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, StringConstant.DATA_ID) , otherBusinessIdIn));

        List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, userTeamList);
        List<Long> dataIdIn = new ArrayList<>();
        teamEntityList.forEach(team -> dataIdIn.add(team.getId()));
        if (dataIdIn.isEmpty()) {
            return;
        }
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                customerUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case CONTRACT_TEAM:
                contractUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case OPPORTUNITY_TEAM:
                opportunityUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case REFUND_TEAM:
                refundUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case CONTACT_TEAM:
                contactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case SUPPLIER_TEAM:
                supplierUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case SUPPLIER_CONTACT_TEAM:
                supplierContactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case BOMBILL_TEAM:
                bomUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PRODUCTIONORDER_TEAM:
                productionOrderUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PURCHASE_TEAM:
                purchaseUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case WORK_ORDER_TEAM:
                workOrderFlowUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PAY_PLAN_TEAM:
                payPlanUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PAYMENT_TEAM:
                paymentUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case QUOTATION_TEAM:
                quotationUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PAYMENT_BALANCE_TEAM:
                paymentBalanceUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            case PAY_BALANCE_TEAM:
                payBalanceUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, null, del);
                break;
            default:
                break;
        }
    }

    /**
     * 添加客户团队人员
     *
     * @param corpid 公司id
     * @param userId 用户
     * @param dataId 数据id
     * @param isMain 负责协同
     * @throws XbbException
     */
    private void addCustomerUser(String corpid, String userId, Long dataId, Integer isMain,Integer businessType) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("customerId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<CustomerUserEntity> userTeamEntityList = customerUserModel.findEntitys(param);

        UserEntity userEntity = userModel.getByKey(userId, corpid);
        //添加主负责人的时候才
        if (Objects.equals(isMain, BasicConstant.ONE)) {
            List<CustomerRuleEntity> ruleList = new ArrayList<>();
            //公海高级模式兼容老逻辑
            publicSeniorRuleHelp.getPublicSeniorRuleList(corpid,businessType,ruleList,new ArrayList<>());
            Integer type = customerRuleService.canGainCustomer(corpid,userEntity,dataId, ruleList, BasicConstant.ZERO);
            boolean flag = type == 0;
            if (!flag){
                CustomerRuleEnum customerRuleEnum = CustomerRuleEnum.getByCode(type);
                switch (customerRuleEnum){
                    case MAX_CUSTOMER_NUM_RULE:
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.MAX_CUSTOMER_NUM_ERROR);
                    case PRE_PRINCIPAL_RULE:
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001,ErrorMessageConstant.PRE_OWNER_CANNOT_JOIN);
                    case GAIN_RATE_RULE:
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.EXCEED_LIMIT_GAIN);
                    default:
                        break;
                }
            }
        }

        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (CustomerUserEntity customerUserEntity : userTeamEntityList) {
                if (!Objects.equals(customerUserEntity.getIsMain(), isMain) && !Objects.equals(customerUserEntity.getIsMain(), BasicConstant.ONE)) {
                    customerUserEntity.setIsMain(isMain);
                    customerUserEntity.setDistributionTime(DateTimeUtil.getInt());
                    customerUserModel.save(customerUserEntity);
                }
            }
        } else {
            createCustomerUser(corpid, userId, dataId, isMain);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(CustomerManagementEnum.DISTRIBUTION_DATE.getAttr(),DateTimeUtil.getInt());
        proUpdateHelp.update(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),corpid,dataId,jsonObject);

        //当设置主负责人时，更新捞取频次
        if (Objects.equals(isMain, BasicConstant.ONE)) {
            customerRuleService.updateGainRateToRedis(corpid, userEntity);
        }
    }

    /**
     * 添加联系人团队人员
     *
     * @param corpid 公司id
     * @param userId 用户
     * @param dataId
     * @param isMain 负责协同数据id
     * @throws XbbException
     */
    private void addContactUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("contactId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<ContactUserEntity> userTeamEntityList = contactUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (ContactUserEntity contactUserEntity : userTeamEntityList) {
                if (!Objects.equals(contactUserEntity.getIsMain(), isMain) && !Objects.equals(contactUserEntity.getIsMain(), BasicConstant.ONE)) {
                    contactUserEntity.setIsMain(isMain);
                    contactUserModel.save(contactUserEntity);
                }
            }
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = proGetHelp.getByKey(dataId, RedundantTemplateTypeEnum.CONTACT.getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
            Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), ContactEnum.CUSTOMER_NAME.getAttr(), 0L);
            createContactUser(corpid, userId, customerId, dataId, isMain);
        }
    }

    /**
     * 添加合同团队人员
     *
     * @param corpid 公司id
     * @param userId 用
     * @param dataId 数据id
     * @param isMain 负责协同
     * @throws XbbException
     */
    private void addContractUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("contractId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<ContractUserEntity> userTeamEntityList = contractUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (ContractUserEntity contractUserEntity : userTeamEntityList) {
                if (!Objects.equals(contractUserEntity.getIsMain(), isMain) && !Objects.equals(contractUserEntity.getIsMain(), BasicConstant.ONE)) {
                    contractUserEntity.setIsMain(isMain);
                    contractUserModel.save(contractUserEntity);
                }
            }
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = proGetHelp.getByKey(dataId,XbbRefTypeEnum.CONTRACT.getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
            Long customerId = paasFormDataEntityExt.getData().getLong(ContractEnum.LINK_CUSTOMER.getAttr());
            createContractUser(corpid, userId, dataId, isMain,customerId);
        }
    }

    private void addContractUserByCustomerId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.CONTRACT.getCode(), ContractEnum.LINK_CUSTOMER.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_CONTRACT);
        List<Long> contractIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> contractIds.add(paasFormDataEntityExt.getId())));
        param.put("contractIdIn", contractIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<ContractUserEntity> withContractUserTeamList = contractUserModel.findEntitys(param);
        if (withContractUserTeamList.size() > BasicConstant.ZERO) {
            for (ContractUserEntity contractUserEntity : withContractUserTeamList) {
                if (!Objects.equals(contractUserEntity.getIsMain(), isMain) && !Objects.equals(contractUserEntity.getIsMain(), BasicConstant.ONE)) {
                    contractUserEntity.setIsMain(isMain);
                    contractUserModel.save(contractUserEntity);
                }
            }
        } else {
            for (Long contractId : contractIds) {
                createContractUser(corpid, userId, contractId, isMain, dataId);
            }
        }
    }

    private void addQuotationUserByCustomerId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.QUOTATION.getCode(), QuotationEnum.CUSTOMER_ID.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_QUOTATION);
        List<Long> quotationIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> quotationIds.add(paasFormDataEntityExt.getId())));
        param.put("quotationIdIn", quotationIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<QuotationUserEntity> withQuotationUserTeamList = quotationUserModel.findEntitys(param);
        if (withQuotationUserTeamList.size() > BasicConstant.ZERO) {
            for (QuotationUserEntity quotationUserEntity : withQuotationUserTeamList) {
                if (!Objects.equals(quotationUserEntity.getIsMain(), isMain) && !Objects.equals(quotationUserEntity.getIsMain(), BasicConstant.ONE)) {
                    quotationUserEntity.setIsMain(isMain);
                    quotationUserModel.save(quotationUserEntity);
                }
            }
        } else {
            for (Long quotationId : quotationIds) {
                createQuotationUser(corpid, userId, quotationId, isMain, dataId);
            }
        }
    }

    /**
     * 添加机会团队人员
     *
     * @param corpid 公司id
     * @param userId 用户
     * @param dataId 数据id
     * @param isMain 负责协同
     * @throws XbbException
     */
    private void addOpportunityUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("opportunityId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<OpportunityUserEntity> userTeamEntityList = opportunityUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (OpportunityUserEntity opportunityUserEntity : userTeamEntityList) {
                if (!Objects.equals(opportunityUserEntity.getIsMain(), isMain) && !Objects.equals(opportunityUserEntity.getIsMain(), BasicConstant.ONE)) {
                    opportunityUserEntity.setIsMain(isMain);
                    opportunityUserModel.save(opportunityUserEntity);
                }
            }
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = proGetHelp.getByKey(dataId,XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
            Long customerId = paasFormDataEntityExt.getData().getLong(SalesOpportunityEnum.CUSTOMER_NAME.getAttr());
            createOpportunityUser(corpid, userId, dataId, isMain, customerId);
        }
    }

    /**
     * 添加报价单团队人员
     *
     * @param corpid 公司id
     * @param userId 用户
     * @param dataId 数据id
     * @param isMain 负责协同
     * @throws XbbException
     */
    private void addQuotationUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("quotationId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<QuotationUserEntity> userTeamEntityList = quotationUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (QuotationUserEntity quotationUserEntity : userTeamEntityList) {
                if (!Objects.equals(quotationUserEntity.getIsMain(), isMain) && !Objects.equals(quotationUserEntity.getIsMain(), BasicConstant.ONE)) {
                    quotationUserEntity.setIsMain(isMain);
                    quotationUserModel.save(quotationUserEntity);
                }
            }
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = proGetHelp.getByKey(dataId, XbbRefTypeEnum.QUOTATION.getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
            Long customerId = paasFormDataEntityExt.getData().getLong(QuotationEnum.CUSTOMER_ID.getAttr());
            createQuotationUser(corpid, userId, dataId, isMain, customerId);
        }
    }

    private void addOpportunityUserByCustomerId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.SALES_OPPORTUNITY.getCode(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        List<Long> opportunityIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> opportunityIds.add(paasFormDataEntityExt.getId())));
        param.put("opportunityIdIn", opportunityIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<OpportunityUserEntity> withOpportunityUserTeamList = opportunityUserModel.findEntitys(param);
        if (withOpportunityUserTeamList.size() > BasicConstant.ZERO) {
            for (OpportunityUserEntity opportunityUserEntity : withOpportunityUserTeamList) {
                if (!Objects.equals(opportunityUserEntity.getIsMain(), isMain) && !Objects.equals(opportunityUserEntity.getIsMain(), BasicConstant.ONE)) {
                    opportunityUserEntity.setIsMain(isMain);
                    opportunityUserModel.save(opportunityUserEntity);
                }
            }
        } else {
            for (Long opportunityId : opportunityIds) {
                createOpportunityUser(corpid, userId, opportunityId, isMain,dataId);
            }
        }
    }

    /**
     * 添加供应商团队人员
     *
     * @param corpid 公司id
     * @param userId 用户
     * @param dataId 数据id
     * @param isMain 负责协同
     * @throws XbbException
     */
    private void addSuplierUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("supplierId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<SupplierUserEntity> userTeamEntityList = supplierUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (SupplierUserEntity supplierUserEntity : userTeamEntityList) {
                if (!Objects.equals(supplierUserEntity.getIsMain(), isMain) && !Objects.equals(supplierUserEntity.getIsMain(), BasicConstant.ONE)) {
                    supplierUserEntity.setIsMain(isMain);
                    supplierUserModel.save(supplierUserEntity);
                }
            }
        } else {
            createSupplierUser(corpid, userId, dataId, isMain);
        }
    }

    private void addPurchaseUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("purchaseId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<PurchaseUserEntity> userTeamEntityList = purchaseUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (PurchaseUserEntity purchaseUserEntity : userTeamEntityList) {
                if (!Objects.equals(purchaseUserEntity.getIsMain(), isMain) && !Objects.equals(purchaseUserEntity.getIsMain(), BasicConstant.ONE)) {
                    purchaseUserEntity.setIsMain(isMain);
                    purchaseUserModel.save(purchaseUserEntity);
                }
            }
        } else {
            createPurchaseUser(corpid, userId, dataId, isMain);
        }
    }

    private void addBomBillUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("bomId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<BomUserEntity> userTeamEntityList = bomUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (BomUserEntity bomUserEntity : userTeamEntityList) {
                if (!Objects.equals(bomUserEntity.getIsMain(), isMain) && !Objects.equals(bomUserEntity.getIsMain(), BasicConstant.ONE)) {
                    bomUserEntity.setIsMain(isMain);
                    bomUserModel.save(bomUserEntity);
                }
            }
        } else {
            createBomBillUser(corpid, userId, dataId, isMain);
        }
    }

    private void addProductionOrderUser(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("productionOrderId", dataId);
        param.put(ParameterConstant.USER_ID, userId);
        List<ProductionOrderUserEntity> userTeamEntityList = productionOrderUserModel.findEntitys(param);
        if (userTeamEntityList.size() > BasicConstant.ZERO) {
            for (ProductionOrderUserEntity productionOrderUserEntity : userTeamEntityList) {
                if (!Objects.equals(productionOrderUserEntity.getIsMain(), isMain) && !Objects.equals(productionOrderUserEntity.getIsMain(), BasicConstant.ONE)) {
                    productionOrderUserEntity.setIsMain(isMain);
                    productionOrderUserModel.save(productionOrderUserEntity);
                }
            }
        } else {
            createProductionOrderUser(corpid, userId, dataId, isMain);
        }

    }
    /**
     * 根据客户id添加退货退款负责团队
     * 用于客户详情添加负责人，不会有新团队创建
     * @param corpid 公司id
     * @param userId 添加人
     * @param dataId 合同id
     * @param isMain 主负责人
     * @throws XbbException
     */
    private void addRefundUserByCustomerId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.REFUND.getCode(), RefundEnum.CUSTOMER_ID.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_REFUND);
        List<Long> refundIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> refundIds.add(paasFormDataEntityExt.getId())));
        if (refundIds.isEmpty()){
            return;
        }
        Map<Long,Long> refundMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt) -> {
            refundIds.add(paasFormDataEntityExt.getId());
            refundMap.put(paasFormDataEntityExt.getId(),paasFormDataEntityExt.getData().getLong(RefundEnum.CONTRACT_ID.getAttr()));
        });
        param.put("refundIdIn", refundIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<RefundUserEntity> withOpportunityUserTeamList = refundUserModel.findEntitys(param);
        for (RefundUserEntity refundUserEntity : withOpportunityUserTeamList) {
            if (!Objects.equals(refundUserEntity.getIsMain(), isMain) && !Objects.equals(refundUserEntity.getIsMain(), BasicConstant.ONE)) {
                //TODO haibin.zhang 此类所有方法,可以有批量解决方案
                refundUserEntity.setIsMain(isMain);
                refundUserModel.save(refundUserEntity);
                refundIds.remove(refundUserEntity.getDataId());
            }
        }
        if (!refundIds.isEmpty()){
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            List<RefundUserEntity> refundUserEntityList = new ArrayList<>();
            //TODO 批量插入团队，其他业务可能也会有这个，通用
            for (Long refund : refundIds) {
                RefundUserEntity refundUserEntity = new RefundUserEntity();
                initEntity(refundUserEntity, userEntity);
                refundUserEntity.setCustomerId(dataId);
                refundUserEntity.setContractId(refundMap.get(refund));
                refundUserEntity.setDataId(refund);
                refundUserEntity.setIsMain(isMain);
                refundUserEntityList.add(refundUserEntity);
            }
            refundUserModel.insertBatch(refundUserEntityList, false);
        }
    }

    /**
     * 根据客户id添加回款负责团队
     * 用于客户详情添加负责人，不会有新团队创建
     * @param corpid 公司id
     * @param userId 添加人
     * @param dataId 合同id
     * @param isMain 主负责人
     * @throws XbbException
     */
    private void addPaymentUserByCustomerId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.PAYMENT.getCode(), PaymentEnum.CUSTOMER.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_PAYMENT);
        List<Long> paymentIds = new ArrayList<>();
        Map<Long,Long> paymentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasFormDataEntityExts.forEach((paasFormDataEntityExt) -> {
            paymentIds.add(paasFormDataEntityExt.getId());
            paymentMap.put(paasFormDataEntityExt.getId(),paasFormDataEntityExt.getData().getLong(PaymentEnum.CONTRACT.getAttr()));
        });
        if (paymentIds.isEmpty()){
            return;
        }
        param.put("paymentIdIn", paymentIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<PaymentUserEntity> withOpportunityUserTeamList = paymentUserModel.findEntitys(param);
        for (PaymentUserEntity paymentUserEntity : withOpportunityUserTeamList) {
            if (!Objects.equals(paymentUserEntity.getIsMain(), isMain) && !Objects.equals(paymentUserEntity.getIsMain(), BasicConstant.ONE)) {
                //TODO haibin.zhang 此类所有方法,可以有批量解决方案
                paymentUserEntity.setIsMain(isMain);
                paymentUserModel.save(paymentUserEntity);
                paymentIds.remove(paymentUserEntity.getDataId());
            }
        }
        if (!paymentIds.isEmpty()){
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            List<PaymentUserEntity> paymentUserEntityList = new ArrayList<>();
            for (Long paymentId : paymentIds){
                PaymentUserEntity paymentUserEntity = new PaymentUserEntity();
                initEntity(paymentUserEntity, userEntity);
                paymentUserEntity.setCustomerId(dataId);
                paymentUserEntity.setContractId(paymentMap.get(paymentId));
                paymentUserEntity.setDataId(paymentId);
                paymentUserEntity.setIsMain(isMain);
                paymentUserEntityList.add(paymentUserEntity);
            }
            paymentUserModel.insertBatch(paymentUserEntityList);
        }
    }

    /**
     * 根据合同id添加回款负责团队
     * 用于合同详情添加负责人，不会有新团队创建
     * @param corpid 公司id
     * @param userId 添加人
     * @param dataId 合同id
     * @param isMain 主负责人
     * @throws XbbException
     */
    private void addPaymentUserByContractId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.PAYMENT.getCode(), PaymentEnum.CONTRACT.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_PAYMENT);
        List<Long> paymentIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> paymentIds.add(paasFormDataEntityExt.getId())));
        if (paymentIds.isEmpty()){
            return;
        }
        Long customerId = paasFormDataEntityExts.get(0).getData().getLong(PaymentEnum.CUSTOMER.getAttr());
        param.put("paymentIdIn", paymentIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<PaymentUserEntity> withOpportunityUserTeamList = paymentUserModel.findEntitys(param);
        for (PaymentUserEntity paymentUserEntity : withOpportunityUserTeamList) {
            if (!Objects.equals(paymentUserEntity.getIsMain(), isMain) && !Objects.equals(paymentUserEntity.getIsMain(), BasicConstant.ONE)) {
                //TODO haibin.zhang 此类所有方法,可以有批量解决方案
                paymentUserEntity.setIsMain(isMain);
                paymentUserModel.save(paymentUserEntity);
                paymentIds.remove(paymentUserEntity.getDataId());
            }
        }
        if (!paymentIds.isEmpty()){
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            List<PaymentUserEntity> paymentUserEntityList = new ArrayList<>();
            //TODO 批量插入团队，其他业务可能也会有这个，通用
            for (Long paymentId : paymentIds) {
                PaymentUserEntity paymentUserEntity = new PaymentUserEntity();
                initEntity(paymentUserEntity, userEntity);
                paymentUserEntity.setCustomerId(customerId);
                paymentUserEntity.setContractId(dataId);
                paymentUserEntity.setDataId(paymentId);
                paymentUserEntity.setIsMain(isMain);
                paymentUserEntityList.add(paymentUserEntity);
            }
            paymentUserModel.insertBatch(paymentUserEntityList);
        }
    }

    /**
     * 根据采购合同id添加付款负责团队
     * 用于采购合同详情添加负责人，不会有新团队创建
     * @param corpid 公司id
     * @param userId 添加人
     * @param dataId 合同id
     * @param isMain 主负责人
     * @throws XbbException
     */
    private void addPayPlanUserByPurchaseId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.PAY_PLAN.getCode(), PayPlanEnum.LINK_PURCHASE.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_PAY_PLAN);
        List<Long> payPlanIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> payPlanIds.add(paasFormDataEntityExt.getId())));
        if (payPlanIds.isEmpty()){
            return;
        }
        Long supplierId = paasFormDataEntityExts.get(0).getData().getLong(PayPlanEnum.LINK_SUPPLIER.getAttr());
        param.put("payPlanIdIn", payPlanIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<PayPlanUserEntity> withOpportunityUserTeamList = payPlanUserModel.findEntitys(param);
        for (PayPlanUserEntity payPlanUserEntity : withOpportunityUserTeamList) {
            if (!Objects.equals(payPlanUserEntity.getIsMain(), isMain) && !Objects.equals(payPlanUserEntity.getIsMain(), BasicConstant.ONE)) {
                //TODO haibin.zhang 此类所有方法,可以有批量解决方案
                payPlanUserEntity.setIsMain(isMain);
                payPlanUserModel.save(payPlanUserEntity);
            }
            payPlanIds.remove(payPlanUserEntity.getDataId());
        }
        if (!payPlanIds.isEmpty()){
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            List<PayPlanUserEntity> payPlanUserEntityList = new ArrayList<>();
            //TODO 批量插入团队，其他业务可能也会有这个，通用
            for (Long payPlanId : payPlanIds) {
                PayPlanUserEntity payPlanUserEntity = new PayPlanUserEntity();
                initEntity(payPlanUserEntity, userEntity);
                payPlanUserEntity.setSupplierId(supplierId);
                payPlanUserEntity.setPurchaseId(dataId);
                payPlanUserEntity.setDataId(payPlanId);
                payPlanUserEntity.setIsMain(isMain);
                payPlanUserEntityList.add(payPlanUserEntity);
            }
            if (!payPlanUserEntityList.isEmpty()) {
                payPlanUserModel.insertBatch(payPlanUserEntityList);
            }
        }
    }


    /**
     * 根据合同id添加退货退款负责团队
     * 用于合同详情添加负责人，不会有新团队创建
     * @param corpid 公司id
     * @param userId 添加人
     * @param dataId 合同id
     * @param isMain 主负责人
     * @throws XbbException
     */
    private void addRefundUserByContractId(String corpid, String userId, Long dataId, Integer isMain) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.REFUND.getCode(), RefundEnum.CONTRACT_ID.getAttr(), dataId.toString(), param, IndexTypeEnum.IDX_SAAS_REFUND);
        List<Long> refundIds = new ArrayList<>();
        paasFormDataEntityExts.forEach((paasFormDataEntityExt -> refundIds.add(paasFormDataEntityExt.getId())));
        if (refundIds.isEmpty()){
            return;
        }
        Long customerId = paasFormDataEntityExts.get(0).getData().getLong(PaymentEnum.CUSTOMER.getAttr());
        param.put("refundIdIn", refundIds);
        param.put(ParameterConstant.USER_ID, userId);
        List<RefundUserEntity> withOpportunityUserTeamList = refundUserModel.findEntitys(param);
        for (RefundUserEntity refundUserEntity : withOpportunityUserTeamList) {
            if (!Objects.equals(refundUserEntity.getIsMain(), isMain) && !Objects.equals(refundUserEntity.getIsMain(), BasicConstant.ONE)) {
                //TODO haibin.zhang 此类所有方法,可以有批量解决方案
                refundUserEntity.setIsMain(isMain);
                refundUserModel.save(refundUserEntity);
                refundIds.remove(refundUserEntity.getDataId());
            }
        }
        if (!refundIds.isEmpty()){
            UserEntity userEntity = userModel.getByKey(userId,corpid);
            List<RefundUserEntity> refundUserEntityList = new ArrayList<>();
            //TODO 批量插入团队，其他业务可能也会有这个，通用
            for (Long refund : refundIds) {
                RefundUserEntity refundUserEntity = new RefundUserEntity();
                initEntity(refundUserEntity, userEntity);
                refundUserEntity.setCustomerId(customerId);
                refundUserEntity.setContractId(dataId);
                refundUserEntity.setDataId(refund);
                refundUserEntity.setIsMain(isMain);
                refundUserEntityList.add(refundUserEntity);
            }
            refundUserModel.insertBatch(refundUserEntityList, false);
        }
    }

    /**
     * 初始化团队人员
     *
     * @param userTeamEntity 团队人员基本实体
     * @param userEntity     人员
     * @return 是否新建
     */
    private void initEntity(UserTeamEntity userTeamEntity, UserEntity userEntity) {
        userTeamEntity.setCorpid(userEntity.getCorpid());
        userTeamEntity.setUserId(userEntity.getUserId());
        userTeamEntity.setUserName(userEntity.getName());
        userTeamEntity.setUserAvatar(userEntity.getAvatar());
    }

    /**
     * 以存在的团队成员，变更isMian校验
     * 不变不入库
     * 降级不入库
     *
     * @param isMain       当前isMian
     * @param targetIsMain 目标修改isMian
     * @return 是否需要更新入库
     */
    public Boolean judgeIdentity(Integer isMain, Integer targetIsMain) {
        if (Objects.equals(isMain, targetIsMain)) {
            return false;
        } else {
            return !Objects.equals(isMain, MAIN_USER) || !Objects.equals(targetIsMain, CO_USER);
        }
    }

    @Override
    public Map<Long, String> getMainUserMap(Collection<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic) {
        List<UserTeamEntity> userTeamEntityList = userTeamHelp.getUserTeamList(dataIdList, corpid, businessType, isPublic, MAIN_USER);
        Map<Long, String> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (UserTeamEntity entity : userTeamEntityList) {
            String name = "";
            if (mainUserMap.containsKey(entity.getDataId())) {
                name += mainUserMap.get(entity.getDataId()) + ",";
            }
            mainUserMap.put(entity.getDataId(), name + entity.getUserName());
        }
        return mainUserMap;
    }

    @Override
    public Map<Long, List<UserTeamEntity>> getMainUserTeamListMap(Collection<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic) {

        List<UserTeamEntity> userTeamEntityList = userTeamHelp.getUserTeamList(dataIdList, corpid, businessType, isPublic, MAIN_USER);
        Map<Long, List<UserTeamEntity>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (UserTeamEntity entity : userTeamEntityList) {
            if (mainUserMap.containsKey(entity.getDataId())) {
                List<UserTeamEntity> userTeamEntities = mainUserMap.get(entity.getDataId());
                userTeamEntities.add(entity);
                mainUserMap.put(entity.getDataId(), userTeamEntities);
            } else {
                List<UserTeamEntity> userTeamEntities = new ArrayList<>();
                userTeamEntities.add(entity);
                mainUserMap.put(entity.getDataId(), userTeamEntities);
            }
        }
        return mainUserMap;
    }

    @Override
    public Map<Integer, List<UserTeamEntity>> getUserTeam(Long dataId, String corpid, Integer businessType) {
        Map<Integer, List<UserTeamEntity>> teamMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.isNull(dataId)) {
            return teamMap;
        }
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<UserTeamEntity> userTeamEntityList = new ArrayList<>();
        map.put(ParameterConstant.CORPID, corpid);
        map.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                map.put("customerId", dataId);
                userTeamEntityList = customerUserModel.findBaseEntitys(map);
                break;
            case CONTACT_TEAM:
                map.put("contactId", dataId);
                userTeamEntityList = contactUserModel.findBaseEntitys(map);
                break;
            case OPPORTUNITY_TEAM:
                map.put("opportunityId", dataId);
                userTeamEntityList = opportunityUserModel.findBaseEntitys(map);
                break;
            case CONTRACT_TEAM:
                map.put("contractId", dataId);
                userTeamEntityList = contractUserModel.findBaseEntitys(map);
                break;
            case QUOTATION_TEAM:
                map.put("quotationId", dataId);
                userTeamEntityList = quotationUserModel.findBaseEntitys(map);
                break;
            case SUPPLIER_TEAM:
                map.put("supplierId", dataId);
                userTeamEntityList = supplierUserModel.findBaseEntitys(map);
                break;
            case PURCHASE_TEAM:
                map.put("purchaseId", dataId);
                userTeamEntityList = purchaseUserModel.findBaseEntitys(map);
                break;
            case BOMBILL_TEAM:
                map.put("bomId", dataId);
                userTeamEntityList = bomUserModel.findBaseEntitys(map);
                break;
            case PRODUCTIONORDER_TEAM:
                map.put("productionOrderId", dataId);
                userTeamEntityList = productionOrderUserModel.findBaseEntitys(map);
                break;
            case WORK_ORDER_TEAM:
                map.put("workOrderId", dataId);
                userTeamEntityList = workOrderFlowUserModel.findBaseEntitys(map);
                break;
            case REFUND_TEAM:
                map.put("refundId", dataId);
                userTeamEntityList = refundUserModel.findBaseEntitys(map);
                break;
            case MARKET_ACTIVITY_TEAM:
                map.put("dataId", dataId);
                userTeamEntityList = marketActivityUserModel.findBaseEntitys(map);
                break;
            case CLUE_TEAM:
                map.put("dataId", dataId);
                userTeamEntityList = clueUserModel.findBaseEntitys(map);
                break;
            case WAREHOUSE_TEAM:
                map.put("dataId", dataId);
                map.put("type",BasicConstant.ZERO);
                List<WarehouseUserEntity> warehouseUserEntityList = warehouseUserModel.findEntitys(map);
                userTeamEntityList = warehouseTeamTransferSubForm.transferWarehouseUserToUserTeam(warehouseUserEntityList);
                break;
            case PAYMENT_TEAM:
                map.put("dataId", dataId);
                userTeamEntityList = paymentUserModel.findBaseEntitys(map);
                break;
            case PAYMENT_SHEET_TEAM:
                map.put("dataId", dataId);
                userTeamEntityList = paymentSheetUserModel.findBaseEntitys(map);
                break;
            case PAY_PLAN_TEAM:
                map.put("dataId", dataId);
                userTeamEntityList = payPlanUserModel.findBaseEntitys(map);
                break;
            case PAY_SHEET_TEAM:
                map.put("dataId", dataId);
                userTeamEntityList = payPlanSheetUserModel.findBaseEntitys(map);
                break;
            case SUPPLIER_CONTACT_TEAM:
                map.put("dataId", dataId);
                userTeamEntityList = supplierContactUserModel.findBaseEntitys(map);
                break;
            default:
                return new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }


        List<UserTeamEntity> mainUserTeamList = new ArrayList<>();
        List<UserTeamEntity> copUserTeamList = new ArrayList<>();
        userTeamEntityList.forEach((userTeamEntity -> {
            if (Objects.equals(userTeamEntity.getIsMain(), MAIN_USER)) {
                mainUserTeamList.add(userTeamEntity);
                teamMap.put(MAIN_USER, mainUserTeamList);
            } else {
                copUserTeamList.add(userTeamEntity);
                teamMap.put(CO_USER, copUserTeamList);
            }
        }));
        return teamMap;
    }



    @Override
    public List<UserTeamEntity> batchGetUserTeam(List<Long> dataIdList, String corpid, Integer businessType) {
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<UserTeamEntity> userTeamEntityList;
        map.put(ParameterConstant.CORPID, corpid);
        map.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
            case CONTACT_TEAM:
                map.put("customerIdIn", dataIdList);
                userTeamEntityList = customerUserModel.findBaseEntitys(map);
                break;
            case OPPORTUNITY_TEAM:
                map.put("opportunityIdIn", dataIdList);
                userTeamEntityList = opportunityUserModel.findBaseEntitys(map);
                break;
            case CONTRACT_TEAM:
                map.put("contractIdIn", dataIdList);
                userTeamEntityList = contractUserModel.findBaseEntitys(map);
                break;
            case QUOTATION_TEAM:
                map.put("quotationIdIn", dataIdList);
                userTeamEntityList = quotationUserModel.findBaseEntitys(map);
                break;
            case SUPPLIER_TEAM:
                map.put("supplierIdIn", dataIdList);
                userTeamEntityList = supplierUserModel.findBaseEntitys(map);
                break;
            case PURCHASE_TEAM:
                map.put("purchaseIdIn", dataIdList);
                userTeamEntityList = purchaseUserModel.findBaseEntitys(map);
                break;
            case BOMBILL_TEAM:
                map.put("bomIdIn", dataIdList);
                userTeamEntityList = bomUserModel.findBaseEntitys(map);
                break;
            case PRODUCTIONORDER_TEAM:
                map.put("productionOrderIdIn", dataIdList);
                userTeamEntityList = productionOrderUserModel.findBaseEntitys(map);
                break;
            case CLUE_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = clueUserModel.findBaseEntitys(map);
                break;
            case COMMUNICATE_PLAN_TEAM:
                map.put("dataIdIn", dataIdList);
                userTeamEntityList = communicatePlanUserModel.findBaseEntitys(map);
                break;
            default:
                userTeamEntityList = new ArrayList<>();
                break;
        }

       return userTeamEntityList;
    }
    /**
     * 获取团队数目是否大于0
     *
     * @param corpid       公司id
     * @param userId       员工id
     * @param dataId       数据id
     * @param businessType 业务类型
     * @param isMain       是否主负责人
     * @return 是否大于0
     */
    @Override
    public boolean getUserTeamList4CheckBeyondZero(String corpid, String userId, Long dataId, Integer businessType, Integer isMain) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.USER_ID, userId);
        param.put(ParameterConstant.IS_MAIN, isMain);
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        List<UserTeamEntity> userTeamEntityList = new ArrayList<>();
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
            case CONTACT_TEAM:
                param.put("customerId", dataId);
                userTeamEntityList = customerUserModel.findBaseEntitys(param);
                break;
            case OPPORTUNITY_TEAM:
                param.put("opportunityId", dataId);
                userTeamEntityList = opportunityUserModel.findBaseEntitys(param);
                break;
            case CONTRACT_TEAM:
                param.put("contractId", dataId);
                userTeamEntityList = contractUserModel.findBaseEntitys(param);
                break;
            case QUOTATION_TEAM:
                param.put("quotationId", dataId);
                userTeamEntityList = quotationUserModel.findBaseEntitys(param);
                break;
            case SUPPLIER_TEAM:
            case SUPPLIER_CONTACT_TEAM:
                param.put(ParameterConstant.SUPPLIER_ID, dataId);
                userTeamEntityList = supplierUserModel.findBaseEntitys(param);
                break;
            case PURCHASE_TEAM:
                param.put(ParameterConstant.PURCHASE_ID, dataId);
                userTeamEntityList = purchaseUserModel.findBaseEntitys(param);
                break;
            case BOMBILL_TEAM:
                param.put(ParameterConstant.BOM_ID, dataId);
                userTeamEntityList = bomUserModel.findBaseEntitys(param);
                break;
            case PRODUCTIONORDER_TEAM:
                param.put(ParameterConstant.PRODUCTION_ORDER_ID, dataId);
                userTeamEntityList = productionOrderUserModel.findBaseEntitys(param);
                break;
            case REFUND_TEAM:
                param.put("refundId", dataId);
                userTeamEntityList = refundUserModel.findBaseEntitys(param);
                break;
            case CLUE_TEAM:
                param.put("dataId", dataId);
                userTeamEntityList = clueUserModel.findBaseEntitys(param);
                break;
            default:
                break;
        }
        return userTeamEntityList.size() > BasicConstant.ZERO;
    }


    @Override
    public Map<Long, List<UserTeamEntity>> getCoUserMap(Collection<Long> dataIdList, String corpid, Integer businessType) {
        List<UserTeamEntity> userTeamEntityList = userTeamHelp.getUserTeamList(dataIdList, corpid, businessType, false , CO_USER);
        Map<Long, List<UserTeamEntity>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (UserTeamEntity entity : userTeamEntityList) {
            if (coUserMap.containsKey(entity.getDataId())) {
                List<UserTeamEntity> userTeamEntities = coUserMap.get(entity.getDataId());
                userTeamEntities.add(entity);
                coUserMap.put(entity.getDataId(), userTeamEntities);
            } else {
                List<UserTeamEntity> userTeamEntities = new ArrayList<>();
                userTeamEntities.add(entity);
                coUserMap.put(entity.getDataId(), userTeamEntities);
            }

        }
        return coUserMap;
    }

    @Override
    public Map<Long, String> getProductUserMap(Collection<Long> dataIdList, String corpid, Integer businessType, Integer type) {
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("type",type);
        map.put("del",0);
        List<UserAndDepTeamEntity> userAndDepTeamEntityList;
        switch (userTeamEnum){
            case PRODUCT_TEAM:
                map.put("productIdIn",dataIdList);
                userAndDepTeamEntityList = productUserModel.findBaseEntitys(map);
                break;
            case WAREHOUSE_TEAM:
                map.put("warehouseIdIn",dataIdList);
                userAndDepTeamEntityList = warehouseUserModel.findBaseEntitys(map);
                break;
            default:
                return new HashMap<>();
        }
        Set<String> userIdSet = new HashSet<>();
        Set<Long> depIdSet = new HashSet<>();
        for (UserAndDepTeamEntity entity : userAndDepTeamEntityList){
            if (Objects.equals(entity.getType(), 1)) {
                try {
                    depIdSet.add(Long.valueOf(entity.getRelationId()));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            } else {
                userIdSet.add(entity.getRelationId());
            }
        }
        Map<Long,DepartmentEntity> depNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,String> userNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(type,1)){
            depNameMap = departmentModel.getDeptsMap(corpid,new ArrayList<>(depIdSet));
        }else {
            userNameMap = userModel.getUserNameMap(corpid,new ArrayList<>(userIdSet));
        }
        Map<Long, String> productUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (UserAndDepTeamEntity entity : userAndDepTeamEntityList){
            String name = productUserMap.getOrDefault(entity.getDataId(),"");
            name = name.isEmpty() ? name: name + "," ;
            if (Objects.equals(type,1)){
                name += depNameMap.get(Long.valueOf(entity.getRelationId())).getName();
            }else {
                name += userNameMap.get(entity.getRelationId());
            }
            productUserMap.put(entity.getDataId(),name);
        }
        return productUserMap;
    }

    @Override
    public boolean updateCustomerTeam(UserEntity user, List<Long> customerIdList, UpdateCustomerTeamScenesEnum updateCustomerTeamScenesEnum, Long formId, Integer saasMark, Integer businessType, Integer distributorMark,String groupId) throws XbbException{
        String corpid = user.getCorpid();
        String userId = user.getUserId();
        List<String> userIdIn = new ArrayList<>();
        if (Objects.equals(updateCustomerTeamScenesEnum, UpdateCustomerTeamScenesEnum.USER_LEAVE)) {
            // 离职只将自己团队退出
            userIdIn = Arrays.asList(userId);
        } else {
            // 查询自己数据权限内的员工，从客户的负责团队移除 （1包含离职员工， false不排除自己）
            Integer dataPermission = userModel.getDataPermission(user, SaasMarkEnum.SAAS, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), null);
            userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userId, corpid, BasicConstant.ONE, false);
        }
        //先查出所有的客户团队
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("customerIdIn",customerIdList);
        map.put("del",0);
        List<CustomerUserEntity> customerUserEntityList = customerUserModel.findEntitys(map);
        //记录要删除的负责人和协同人的id
        Set<String> delOwnerIdIn = new HashSet<>();
        Set<String> delCoUserIdIn = new HashSet<>();
        //查出所有客户的所有负责人
        List<CustomerUserEntity> ownerCustomerUserEntityList = customerUserEntityList.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ONE)).collect(Collectors.toList());
        for (CustomerUserEntity customerUserEntity : customerUserEntityList) {
            if(Objects.equals(customerUserEntity.getIsMain(),Constant.ZERO) && userIdIn.contains(customerUserEntity.getUserId())){
                delCoUserIdIn.add(customerUserEntity.getUserId());
            }else if(Objects.equals(customerUserEntity.getIsMain(),Constant.ONE) && userIdIn.contains(customerUserEntity.getUserId())){
                delOwnerIdIn.add(customerUserEntity.getUserId());
            }
        }

        Set<Long> multiCustomerIdList = new HashSet<>();
        // userNameMap: 记录要退出的人名
        Map<Long, StringBuffer> userNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<CustomerUserEntity>> customerIdToUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 下面的记录跟进记录感觉有bug，此处改一下
        Set<Long> customerIds = new HashSet<>();
        for (CustomerUserEntity entity : ownerCustomerUserEntityList){
            if (!userIdIn.contains(entity.getUserId())) {
                multiCustomerIdList.add(entity.getDataId());
            } else {
                Long customerId = entity.getDataId();
                if (userNameMap.containsKey(customerId)) {
                    StringBuffer userName = userNameMap.get(customerId);
                    userNameMap.put(customerId, userName.append("、").append(entity.getUserName()));
                    customerIdToUserMap.get(customerId).add(entity);
                } else {
                    userNameMap.put(customerId, new StringBuffer(entity.getUserName()));
                    customerIdToUserMap.computeIfAbsent(customerId, k -> new ArrayList<>()).add(entity);
                }
            }
            customerIds.add(entity.getDataId());
        }

        List<CustomerDynamicAddDTO> customerDynamicAddDTOList = new ArrayList<>();
        boolean userBack = Objects.equals(updateCustomerTeamScenesEnum, UpdateCustomerTeamScenesEnum.USER);
        if (userBack) {
            //多负责人团队仅退出 自己数据权限内的员工（multiCustomerIdList 存的是 除去要移除的员工后 还有负责人的客户）
            if (!multiCustomerIdList.isEmpty()) {
                //更新团队
                TeamUpdateMidPOJO teamUpdateMidPOJO = new TeamUpdateMidPOJO(corpid,new ArrayList<>(multiCustomerIdList),formId,saasMark,businessType,
                        distributorMark, null, delOwnerIdIn,null, delCoUserIdIn,null, false, false);
                TeamAfterVerifyDTO teamAfterVerifyDTO = teamDataHelp.basicVerify(teamUpdateMidPOJO,null);
                teamAfterVerifyDTO.setIsBack(true);
                teamDataHelp.batchUpdateTeam(teamAfterVerifyDTO);
            }

            //去除多负责人团队客户
            customerIdList.removeAll(new ArrayList<>(multiCustomerIdList));
            LOG.info("updateCustomerTeam() , customerIdList: {}",customerIdList);
            if (!customerIdList.isEmpty()) {
                //单负责人团队就地解散
                teamDataHelp.disbandedTeam(corpid,formId,saasMark,businessType,distributorMark,customerIdList,updateCustomerTeamScenesEnum);
                //更新数据isPbulic和退回次数值
                updatePublicAndBackNum(customerIdList, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), corpid,groupId);
            }
            LOG.info("更新数据isPbulic和退回次数值成功");

            Runnable runnable = () -> {
                if (!customerIdList.isEmpty()) {
                    // 接触关注
                    customerFocusModel.unFocusBatch(customerIdList, corpid);
                }
                try {
                    if (Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark)) {
                        String communicateMemo = "“" + user.getName()+ "”" + I18nMessageUtil.getMessage(I18nStringConstant.EXIT_RESPONSIBLE_TEAM_OPERATE);
                        for (Long customerId: customerIds) {
                            CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                            customerDynamicAddDTO.setCorpid(corpid);
                            customerDynamicAddDTO.setUserId(userId);
                            String userNames = userNameMap.get(customerId).toString();
                            communicateMemo = String.format(communicateMemo, userNames);
                            customerDynamicAddDTO.setMemo(communicateMemo);
                            customerDynamicAddDTO.setCustomerId(customerId);
                            customerDynamicAddDTO.setCustomerName("");
                            customerDynamicAddDTO.setDataId(0L);
                            customerDynamicAddDTO.setCommunicateBusinessType(null);
                            customerDynamicAddDTO.setCommunicateBusinessText("");
                            customerDynamicAddDTO.setLogType(ProjectLogEnum.CUSTOMER_BACK.getSubType());
                            customerDynamicAddDTO.setDistributorMark(distributorMark);
                            customerDynamicAddDTOList.add(customerDynamicAddDTO);
                        }
                        customerCommunicateService.batchAddCustomerDynamic(customerDynamicAddDTOList,corpid);
                    }else {
                        // 动态
                        CustomerDynamicStrategy customerDynamicStrategy = dynamicStrategyFactory.getCustomerDynamicStrategy(ProjectLogEnum.CUSTOMER_BACK.getSubType());
                        customerDynamicStrategy.backAndExitTeam(DynamicBackAndExitTeamDTO.initBackAndExitTeamDTO(corpid, user, new ArrayList<>(customerIds), userNameMap));
                    }
                } catch (Exception e) {
                    LOG.error("退回公海动态失败", e);
                }

            };
            threadPoolBeanConfig.listBatchThreadPool().execute(runnable);
            return true;
        }
        //多负责人团队仅退出 自己数据权限内的员工（multiCustomerIdList 存的是 除去要移除的员工后 还有负责人的客户）
        if (!multiCustomerIdList.isEmpty()) {
            if (Objects.equals(updateCustomerTeamScenesEnum, UpdateCustomerTeamScenesEnum.USER_LEAVE)) {
                //如果是离职的，还需要判断表单的共享隔离模式
                FormTeamSetEntity formTeamSet = formTeamSetHelp.getFormTeamSet(corpid, formId, saasMark, businessType, distributorMark);
                if(Objects.equals(formTeamSet.getModel(), FormPatternEnum.FORM_ISOLATION.getModel())){
                    //隔离的不操作团队数据

                }else{
                    //更新团队
                    TeamUpdateMidPOJO teamUpdateMidPOJO = new TeamUpdateMidPOJO(corpid,new ArrayList<>(multiCustomerIdList),formId,saasMark,businessType,
                            distributorMark, null, delOwnerIdIn,null, delCoUserIdIn,null, false, false);
                    TeamAfterVerifyDTO teamAfterVerifyDTO = teamDataHelp.basicVerify(teamUpdateMidPOJO,null);
                    teamAfterVerifyDTO.setIsBack(true);
                    teamDataHelp.batchUpdateTeam(teamAfterVerifyDTO);
                }

            }else{
                //更新团队
                TeamUpdateMidPOJO teamUpdateMidPOJO = new TeamUpdateMidPOJO(corpid,new ArrayList<>(multiCustomerIdList),formId,saasMark,businessType,
                        distributorMark, null, delOwnerIdIn,null, delCoUserIdIn,null, false, false);
                TeamAfterVerifyDTO teamAfterVerifyDTO = teamDataHelp.basicVerify(teamUpdateMidPOJO,null);
                teamAfterVerifyDTO.setIsBack(true);
                teamDataHelp.batchUpdateTeam(teamAfterVerifyDTO);
            }

        }
        //去除多负责人团队客户
        if(CollectionsUtil.isNotEmpty(customerIdList) && CollectionsUtil.isNotEmpty(multiCustomerIdList)){
            customerIdList.removeAll(new ArrayList<>(multiCustomerIdList));
        }
        //单负责人团队就地解散
        if (!customerIdList.isEmpty()) {
            teamDataHelp.disbandedTeam(corpid,formId,saasMark,businessType,distributorMark,customerIdList,updateCustomerTeamScenesEnum);
        }
        //解除关注
        if (!customerIdList.isEmpty()) {
            customerFocusModel.unFocusBatch(customerIdList,corpid);
        }

        //更新客户
        if (!customerIdList.isEmpty()) {
            //更新数据isPbulic和退回次数值
            updatePublicAndBackNum(customerIdList, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), corpid,groupId);
        }
        // 记录项目日志
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("idIn", customerIds);
        List<CustomerEntityExt> customerEntityExtList = customerModel.findEntitys(param);
        List<Long> cIds = customerEntityExtList.stream().map(CustomerEntityExt::getId).collect(Collectors.toList());

        if (Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark)) {
            String communicateMemo = "";

            switch (updateCustomerTeamScenesEnum) {
                case PUBLIC_RULE_SCRIPT:
                    communicateMemo = I18nMessageUtil.getMessage(I18nStringConstant.EXIT_RESPONSIBLE_TEAM_SCRIPT);
                    break;
                case USER_LEAVE:
                    communicateMemo = I18nMessageUtil.getMessage(I18nStringConstant.EXIT_RESPONSIBLE_TEAM_RESIGN);
                    break;
                case USER:
                    communicateMemo = "“" + user.getName()+ "”" + I18nMessageUtil.getMessage(I18nStringConstant.EXIT_RESPONSIBLE_TEAM_OPERATE);
                    break;
                default:
                    break;
            }

            for (CustomerEntityExt customerEntityExt: customerEntityExtList) {
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(userId);
                String userNames = userNameMap.get(customerEntityExt.getId()).toString();
                communicateMemo = String.format(communicateMemo, userNames);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCustomerId(customerEntityExt.getId());
                customerDynamicAddDTO.setCustomerName(customerEntityExt.getSerialNo());
                customerDynamicAddDTO.setDataId(0L);
                customerDynamicAddDTO.setCommunicateBusinessType(null);
                customerDynamicAddDTO.setCommunicateBusinessText("");
                customerDynamicAddDTO.setLogType(ProjectLogEnum.CUSTOMER_BACK.getSubType());
                customerDynamicAddDTO.setDistributorMark(distributorMark);
                customerDynamicAddDTOList.add(customerDynamicAddDTO);
            }
            customerCommunicateService.batchAddCustomerDynamic(customerDynamicAddDTOList,corpid);
        } else{
            // 动态
            CustomerDynamicStrategy customerDynamicStrategy = dynamicStrategyFactory.getCustomerDynamicStrategy(ProjectLogEnum.CUSTOMER_BACK.getSubType());
            switch (updateCustomerTeamScenesEnum) {
                case PUBLIC_RULE_SCRIPT:
                    // communicateMemo = I18nStringConstant.EXIT_RESPONSIBLE_TEAM_SCRIPT;
                    // communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_BACK_EXIT_TEAM_SCRIPT;
                    customerDynamicStrategy.scriptBackAndExitTeam(DynamicBackAndExitTeamDTO.initScriptBackAndExitTeamDTO(corpid, user, cIds, customerIdToUserMap));
                    break;
                case USER_LEAVE:
                    // communicateMemo = I18nStringConstant.EXIT_RESPONSIBLE_TEAM_RESIGN;
                    // communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_BACK_EXIT_TEAM_LEAVE
                    customerDynamicStrategy.leaveBackAndExitTeam(DynamicBackAndExitTeamDTO.initLeaveBackAndExitTeamDTO(corpid, user, cIds, customerIdToUserMap));
                    break;
                case USER:
                    // communicateMemo = "“" + user.getName()+ "”" + I18nMessageUtil.getMessage(I18nStringConstant.EXIT_RESPONSIBLE_TEAM_OPERATE);
                    // communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_BACK_EXIT_TEAM;
                    customerDynamicStrategy.backAndExitTeam(DynamicBackAndExitTeamDTO.initBackAndExitTeamDTO(corpid, user, cIds, userNameMap));
                    break;
                default:
                    break;
            }
        }

        return true;
    }


    //更新退回次数逻辑
    private void updatePublicAndBackNum( List<Long> dataIdList, Integer businessType, String corpid,String objectGroupId) throws XbbException {
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        String backNumAtrr = CustomerManagementEnum.BACK_NUM.getAttr();
        String publicAttr =  CustomerManagementEnum.IS_PUBLIC.getAttr();
        String publicDateAttr =  CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr();
        String publicGroup =  CustomerManagementEnum.PUBLIC_GROUP.getAttr();

        if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(),businessType)) {
            backNumAtrr = ClueEnum.BACK_NUM.getAttr();
            publicAttr =  ClueEnum.IS_PUBLIC.getAttr();
            publicDateAttr =  ClueEnum.BACK_PUBLIC_DATE.getAttr();
            publicGroup =  ClueEnum.PUBLIC_GROUP.getAttr();
        }

        //过滤返回字段
        List<String> fieldList = new ArrayList<>();
        fieldList.add(FieldTypeEnum.DATAID.getAlias());
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),businessType)) {
            fieldList.add(CustomerManagementEnum.getAttrConnectData(CustomerManagementEnum.BACK_NUM));
        } else if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(),businessType)) {
            fieldList.add(ClueEnum.getAttrConnectData(ClueEnum.BACK_NUM));
        }
        //维护退回次数并且更新public
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), dataIdList));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
        sourceBuilder.query(boolQueryBuilder);
        String[] strings = new String[fieldList.size()];
        sourceBuilder.fetchSource(fieldList.toArray(strings),null);
        SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, dataIdList.size());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);

        if (CollectionsUtil.isNotEmpty(esEntities.getContent())) {
            List<UpdateDataEntity> updateDataEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            LOG.info("开始更新客户退户次数和公海池标识");
            for (PaasFormDataEntityExt paasFormDataEntityExt : esEntities.getContent()) {
                //退回次数
                Integer backNum = FastJsonHelper.getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(), backNumAtrr, 0);
                //原绑定的公海分组
                String publicGroupId = FastJsonHelper.getStringOrDefault(paasFormDataEntityExt.getData(), publicGroup, "");
                //退回次数集合
                JSONObject temp = new JSONObject();
                temp.put(backNumAtrr, backNum + 1);
                temp.put(publicAttr,1);
                temp.put(publicDateAttr, DateTimeUtil.getInt());
                //如果objectGroupId = "" 或者 objectGroupId = null,代表当前分组是无公海分组,就把这个字段remove掉
                if (StringUtil.isEmpty(objectGroupId) && StringUtil.isEmpty(publicGroupId)){
                    temp.put(publicGroup,"");
                }else if(StringUtil.isNotEmpty(objectGroupId)){
                    temp.put(publicGroup,objectGroupId);
                }
                UpdateDataEntity updateData = ExplainUtil.getUpdateData(paasFormDataEntityExt.getDataId(), temp, corpid);
                updateDataEntityList.add(updateData);
            }
            //批量更新退回次数
            if (CollectionsUtil.isNotEmpty(updateDataEntityList)) {
                proUpdateHelp.updateBatch(1, businessType, corpid, updateDataEntityList);
            }
            LOG.info("更新客户退户次数和公海池标识结束");
        }
    }

    @Override
    public boolean updateClueTeam(UserEntity user, List<Long> clueIdList, UpdateCustomerTeamScenesEnum updateCustomerTeamScenesEnum, Long formId, Integer saasMark, Integer businessType, Integer distributorMark,String groupId) throws XbbException{
        String corpid = user.getCorpid();
        String userId = user.getUserId();
        List<String> userIdIn = new ArrayList<>();
        if (Objects.equals(updateCustomerTeamScenesEnum, UpdateCustomerTeamScenesEnum.USER_LEAVE)) {
            // 离职只将自己团队退出
            userIdIn = Arrays.asList(userId);
        } else {
            // 查询自己数据权限内的员工，从客户的负责团队移除 （1包含离职员工， false不排除自己）
            Integer dataPermission = userModel.getDataPermission(user, SaasMarkEnum.SAAS, XbbRefTypeEnum.CLUE.getCode(), null);
            userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userId, corpid, BasicConstant.ONE, false);
        }
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("dataIdIn",clueIdList);
        map.put("del",0);
        List<ClueUserEntity> clueUserEntities = clueUserModel.findEntitys(map);
        //记录要删除的负责人和协同人的id
        Set<String> delOwnerIdIn = new HashSet<>();
        Set<String> delCoUserIdIn = new HashSet<>();
        //查出所有客户的所有负责人
        List<ClueUserEntity> ownerClueUserEntityList = clueUserEntities.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ONE)).collect(Collectors.toList());
        for (ClueUserEntity clueUserEntity : clueUserEntities) {
            if(Objects.equals(clueUserEntity.getIsMain(),Constant.ZERO) && userIdIn.contains(clueUserEntity.getUserId())){
                delCoUserIdIn.add(clueUserEntity.getUserId());
            }else if(Objects.equals(clueUserEntity.getIsMain(),Constant.ONE) && userIdIn.contains(clueUserEntity.getUserId())){
                delOwnerIdIn.add(clueUserEntity.getUserId());
            }
        }
        Set<Long> multiClueIdList = new HashSet<>();
        // userNameMap: 记录要退出的人名
        Map<Long, StringBuffer> userNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> clueIds = new HashSet<>();
        for (ClueUserEntity entity : ownerClueUserEntityList){
            if (!userIdIn.contains(entity.getUserId())) {
                multiClueIdList.add(entity.getDataId());
            } else {
                Long dataId = entity.getDataId();
                if (userNameMap.containsKey(dataId)) {
                    StringBuffer userName = userNameMap.get(dataId);
                    userNameMap.put(dataId, userName.append("、").append(entity.getUserName()));
                } else {
                    userNameMap.put(dataId, new StringBuffer(entity.getUserName()));
                }
            }
            clueIds.add(entity.getDataId());
        }

        boolean userBack = Objects.equals(updateCustomerTeamScenesEnum, UpdateCustomerTeamScenesEnum.USER);
        if (userBack) {
            //多负责人团队仅退出 自己数据权限内的员工（multiCustomerIdList 存的是 除去要移除的员工后 还有负责人的线索）
            if (!multiClueIdList.isEmpty()) {
                //更新团队
                TeamUpdateMidPOJO teamUpdateMidPOJO = new TeamUpdateMidPOJO(corpid,new ArrayList<>(multiClueIdList),formId,saasMark,businessType,
                        distributorMark, null, delOwnerIdIn,null, delCoUserIdIn,null, false, false);
                TeamAfterVerifyDTO teamAfterVerifyDTO = teamDataHelp.basicVerify(teamUpdateMidPOJO,null);
                teamAfterVerifyDTO.setIsBack(true);
                teamDataHelp.batchUpdateTeam(teamAfterVerifyDTO);
            }

            //去除多负责人团队线索
            clueIdList.removeAll(new ArrayList<>(multiClueIdList));
            if (!clueIdList.isEmpty()) {
                //单负责人团队就地解散
                clueUserModel.disbandedTeam(corpid, clueIdList, null);
                //查线索退回数据
                updatePublicAndBackNum(clueIdList, XbbRefTypeEnum.CLUE.getCode(),corpid,groupId);
            }
            return true;
        }
        //多负责人团队仅退出 自己数据权限内的员工（multiCustomerIdList 存的是 除去要移除的员工后 还有负责人的客户）
        if (!multiClueIdList.isEmpty()) {
            if (Objects.equals(updateCustomerTeamScenesEnum, UpdateCustomerTeamScenesEnum.USER_LEAVE)) {
                //如果是离职的，还需要判断表单的共享隔离模式
                FormTeamSetEntity formTeamSet = formTeamSetHelp.getFormTeamSet(corpid, formId, saasMark, businessType, distributorMark);
                if(Objects.equals(formTeamSet.getModel(), FormPatternEnum.FORM_ISOLATION.getModel())){
                    //隔离的不操作团队数据

                }else{
                    //更新团队
                    TeamUpdateMidPOJO teamUpdateMidPOJO = new TeamUpdateMidPOJO(corpid,new ArrayList<>(multiClueIdList),formId,saasMark,businessType,
                            distributorMark,null,delOwnerIdIn,null,delCoUserIdIn,null, false, false);
                    TeamAfterVerifyDTO teamAfterVerifyDTO = teamDataHelp.basicVerify(teamUpdateMidPOJO,null);
                    teamAfterVerifyDTO.setIsBack(true);
                    teamDataHelp.batchUpdateTeam(teamAfterVerifyDTO);
                }

            }else{
                //更新团队
                TeamUpdateMidPOJO teamUpdateMidPOJO = new TeamUpdateMidPOJO(corpid,new ArrayList<>(multiClueIdList),formId,saasMark,businessType,
                        distributorMark,null,delOwnerIdIn,null,delCoUserIdIn,null, false, false);
                TeamAfterVerifyDTO teamAfterVerifyDTO = teamDataHelp.basicVerify(teamUpdateMidPOJO,null);
                teamAfterVerifyDTO.setIsBack(true);
                teamDataHelp.batchUpdateTeam(teamAfterVerifyDTO);
            }
        }
        LOG.info("clueIdList:{},multiClueIdList:{}",clueIdList,multiClueIdList);
        //去除多负责人团队
        if (CollectionsUtil.isNotEmpty(clueIdList) && CollectionsUtil.isNotEmpty(multiClueIdList)){
            clueIdList.removeAll(new ArrayList<>(multiClueIdList));
        }
        //单负责人团队就地解散
        if (!clueIdList.isEmpty()) {
            clueUserModel.disbandedTeam(corpid, clueIdList, null);
            //teamDataHelp.disbandedTeam(corpid,formId,saasMark,businessType,distributorMark,clueIdList,updateCustomerTeamScenesEnum);
        }
        //更新线索
        if (!clueIdList.isEmpty()) {
//            map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//            map.put(ClueEnum.IS_PUBLIC.getAttr(),1);
//            map.put(ClueEnum.BACK_PUBLIC_DATE.getAttr(),DateTimeUtil.getInt());
//            clueModel.updateBatchNoSub(corpid,clueIdList,map, null);
            updatePublicAndBackNum(clueIdList, XbbRefTypeEnum.CLUE.getCode(),corpid,groupId);
        }
        return true;
    }

    /**
     * 协同团队删除成员消息推送
     *
     * @param  userTeamDelPushDTO 删除成员消息推送入参
     * @author GuoJun.HU
     * @since V1.0
     * @date 2019/4/17 15:38
     * @throws XbbException XbbException
     */
    @Override
    public void pushMessageAfterRemoveUser(UserTeamDelPushDTO userTeamDelPushDTO) throws XbbException {
        String corpid = userTeamDelPushDTO.getCorpid();
        Long dataId = userTeamDelPushDTO.getDataId();
        List<String> updateUserIdIn = userTeamDelPushDTO.getUpdateUserIdIn();
        Integer businessType = userTeamDelPushDTO.getBusinessType();
        boolean isMain = Objects.equals(userTeamDelPushDTO.getIsMain(), 1);
        PaasFormDataEntityExt formDataEntity = saasGetHelp.getFormData(dataId, corpid, businessType);
        if (Objects.isNull(formDataEntity)) {
            return;
        }
        // 业务数据的名称
        String businessDataName = "";
        // 推送类型
        PushTypeEnum pushTypeEnum = null;
        // 推送标题
        String title = "";
        // 推送给删除的人员的内容
        String userContent = "";
        // 推送给消息设置的人员的内容
        String pushContent = "";
        // 推送人员
        List<String> pushUserList = new ArrayList<>();
        // 协同团队类型,经销商需转businessType
        businessType = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, userTeamDelPushDTO.getDistributorMark());
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                businessDataName = formDataEntity.getData().getString(CustomerManagementEnum.NAME.getAttr());
                pushTypeEnum = isMain ? PushTypeEnum.CUSTOMER_TEAM_ADD_DEL_MAIN : PushTypeEnum.CUSTOMER_TEAM_ADD_DEL_SYNERGETIC;
                title = isMain ? I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_DEL_OTHER_CONTENT);
                break;
            case CONTRACT_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.CONTRACT_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.CONTRACT_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_DEL_OTHER_CONTENT);
                break;
            case ORDER_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.ORDER_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.ORDER_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_DEL_OTHER_CONTENT);
                break;
            case QUOTATION_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.QUOTATION_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.QUOTATION_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_DEL_OTHER_CONTENT);
                break;
            case OPPORTUNITY_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.OPPORTUNITY_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.OPPORTUNITY_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_DEL_OTHER_CONTENT);
                break;
            case SUPPLIER_TEAM:
                businessDataName = formDataEntity.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr());
                pushTypeEnum = isMain ? PushTypeEnum.SUPPLIER_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.SUPPLIER_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_DEL_OTHER_CONTENT);
                List<SupplierUserEntity> supplierUserList = supplierUserModel.getSupplierUserListBySupplierId(corpid, dataId);
                for (SupplierUserEntity item : supplierUserList) {
                    pushUserList.add(item.getUserId());
                }
                break;
            case PURCHASE_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.PURCHASE_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.PURCHASE_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_DEL_OTHER_CONTENT);
                List<PurchaseUserEntity> purchaseUserEntities = purchaseUserModel.getPurchaseUserListByPurchaseId(corpid, dataId, null);
                for (PurchaseUserEntity entity : purchaseUserEntities) {
                    pushUserList.add(entity.getUserId());
                }
                break;
            case BOMBILL_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.BOMBILL_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.BOMBILL_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_DEL_MAIN_TITLE): I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_DEL_OTHER_CONTENT);
                List<BomUserEntity> bomUserList = bomUserModel.getBomUserListByBomId(corpid, dataId);
                for (BomUserEntity item : bomUserList) {
                    pushUserList.add(item.getUserId());
                }
                break;
            case PRODUCTIONORDER_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.PRODUCTION_ORDER_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.PRODUCTION_ORDER_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_DEL_OTHER_CONTENT);
                List<ProductionOrderUserEntity> productionOrderUserEntityList = productionOrderUserModel.getProductionOrderUserListByProductionOrderId(corpid, dataId);
                for (ProductionOrderUserEntity item : productionOrderUserEntityList) {
                    pushUserList.add(item.getUserId());
                }
                break;
            case WORK_ORDER_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = PushTypeEnum.WORKORDER_TEAM;
                title = I18nMessageUtil.getMessage(WorkOrderPushConstant.WORK_ORDER_TEAM_DEL_TITLE);
                userContent = I18nMessageUtil.getMessage(WorkOrderPushConstant.TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(WorkOrderPushConstant.TEAM_DEL_OTHER_CONTENT);
                break;
            case DISTRIBUTOR_TEAM:
                businessDataName = formDataEntity.getData().getString(DistributorEnum.NAME.getAttr());
                pushTypeEnum = isMain ? PushTypeEnum.DISTRIBUTOR_TEAM_ADD_DEL_MAIN : PushTypeEnum.DISTRIBUTOR_TEAM_ADD_DEL_SYNERGETIC;
                title = isMain ? I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_DEL_OTHER_CONTENT);
                break;
            case CLUE_TEAM:
                businessDataName = FastJsonHelper.getStringOrDefaultFromFormData(formDataEntity.getData(), ClueEnum.COMPANY_NAME.getAttr(), "");
                pushTypeEnum = isMain ? PushTypeEnum.CLUE_TEAM_ADD_DEL_MAIN : PushTypeEnum.CLUE_TEAM_ADD_DEL_SYNERGETIC;
                title = isMain ? I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_DEL_MAIN_TITLE) : I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_DEL_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_DEL_CONTENT);
                pushContent = I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_DEL_OTHER_CONTENT);
                break;
            default:
                break;
        }
        if (Objects.nonNull(pushTypeEnum) && !Objects.equals(userTeamEnum, UserTeamEnum.UNKNOW)) {
            businessType = XbbRefTypeEnum.transferBusinessType2Index(businessType);
            if (Objects.equals(userTeamEnum, UserTeamEnum.WORK_ORDER_TEAM)) {
                WorkOrderEntity workOrderEntity = new WorkOrderEntity();
                BeanUtil.copyProperties(formDataEntity, workOrderEntity);
                pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, pushTypeEnum.getCode(), pushTypeEnum.getSubCode(), userTeamDelPushDTO.getLoginUser(), workOrderEntity);
            } else if (!Objects.equals(userTeamEnum, UserTeamEnum.SUPPLIER_TEAM) && !Objects.equals(userTeamEnum, UserTeamEnum.BOMBILL_TEAM) &&
                    !Objects.equals(userTeamEnum, UserTeamEnum.PRODUCTIONORDER_TEAM) && !Objects.equals(userTeamEnum, UserTeamEnum.PURCHASE_TEAM)) {
                // 从设置中获取推送人员
                pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, pushTypeEnum.getCode(), pushTypeEnum.getSubCode(), userTeamDelPushDTO.getLoginUser(), formDataEntity);
            }

            UserVO loginUser = userTeamDelPushDTO.getLoginUser();
            if (pushUserList != null && pushUserList.size() > 0) {
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(formDataEntity.getAppId(), formDataEntity.getMenuId(), formDataEntity.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), businessType, businessType);

                if (userTeamEnum.equals(UserTeamEnum.WORK_ORDER_TEAM)) {
                    userContent = String.format(userContent, loginUser.getName(), businessDataName);
                } else {
                    userContent = String.format(userContent, businessDataName);
                }
                if (!(updateUserIdIn.contains(userTeamDelPushDTO.getUserId()) && Objects.equals(updateUserIdIn.size(), 1))) {
                    updateUserIdIn.remove(loginUser.getUserId());
                    MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, updateUserIdIn, Collections.singletonList(dataId), 0, null, title, userContent, null, options);
                    baseProducer.sendMessage(pushTypeEnum, messageRabbitMqDTO);
                }

                Map<String, String> userIdNameMap = userModel.getUserIdNameMap(corpid, updateUserIdIn);
                StringBuilder teamUserNameSb = new StringBuilder();
                for (String name : userIdNameMap.values()) {
                    teamUserNameSb.append(name).append(StringConstant.COMMA);
                }
                String teamUserName = teamUserNameSb.toString();
                if (StringUtil.isNotEmpty(teamUserName)) {
                    teamUserName = teamUserName.substring(0, teamUserName.length() - 1);
                }
                if (userTeamEnum.equals(UserTeamEnum.WORK_ORDER_TEAM)) {
                    pushContent = String.format(pushContent, loginUser.getName(), teamUserName, businessDataName);
                } else {
                    pushContent = String.format(pushContent, teamUserName, businessDataName);
                }
                for (String updateUserId : updateUserIdIn) {
                    pushUserList.remove(updateUserId);
                }
                pushUserList.remove(loginUser.getUserId());
                MessageRabbitMqDTO messageRabbitMqPushSetDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, title, pushContent, null, options);
                baseProducer.sendMessage(pushTypeEnum, messageRabbitMqPushSetDTO);
            }
        }
    }

    @Override
    public void pushMessageAfterAddUser(UserTeamAddPushDTO userTeamAddPushDTO) throws XbbException {
        // 协同团队添加成员消息推送
        String corpid = userTeamAddPushDTO.getCorpid();
        Long dataId = userTeamAddPushDTO.getDataId();
        Integer businessType = userTeamAddPushDTO.getBusinessType();
        boolean isMain = Objects.equals(userTeamAddPushDTO.getIsMain(), 1);
        PaasFormDataEntityExt formDataEntity = saasGetHelp.getFormData(dataId, corpid, businessType);
        if (Objects.isNull(formDataEntity)) {
            return;
        }
        // 业务数据的名称
        String businessDataName = "";
        // 推送类型
        PushTypeEnum pushTypeEnum = null;
        // 推送标题
        String title = "";
        // 推送给添加的人员的内容
        String userContent = "";
        // 推送给消息设置的人员的内容
        String pushContent = "";
        // 推送人员
        List<String> pushUserList = new ArrayList<>();
        // 协同团队类型,经销商需转businessType
        businessType = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, userTeamAddPushDTO.getDistributorMark());
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                businessDataName = formDataEntity.getData().getString(CustomerManagementEnum.NAME.getAttr());
                pushTypeEnum = isMain ? PushTypeEnum.CUSTOMER_TEAM_ADD_DEL_MAIN : PushTypeEnum.CUSTOMER_TEAM_ADD_DEL_SYNERGETIC;
                title = isMain ? I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(CustomerPushConstant.CUSTOMER_TEAM_ADD_OTHER_CONTENT);
                break;
            case CONTRACT_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.CONTRACT_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.CONTRACT_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(ContractPushConstant.CONTRACT_TEAM_ADD_OTHER_CONTENT);
                break;
            case ORDER_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.ORDER_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.ORDER_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(OrderPushConstant.ORDER_TEAM_ADD_OTHER_CONTENT);
                break;
            case OPPORTUNITY_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.OPPORTUNITY_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.OPPORTUNITY_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_TEAM_ADD_OTHER_CONTENT);
                break;
            case SUPPLIER_TEAM:
                businessDataName = formDataEntity.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr());
                pushTypeEnum = isMain ? PushTypeEnum.SUPPLIER_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.SUPPLIER_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(SupplierPushConstant.SUPPLIER_TEAM_ADD_OTHER_CONTENT);
                List<SupplierUserEntity> supplierUserList = supplierUserModel.getSupplierUserListBySupplierId(corpid, dataId);
                for (SupplierUserEntity item : supplierUserList) {
                    pushUserList.add(item.getUserId());
                }
                break;
            case PURCHASE_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.PURCHASE_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.PURCHASE_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(PurchasePushConstant.PURCHASE_TEAM_ADD_OTHER_CONTENT);
                List<PurchaseUserEntity> purchaseUserEntities = purchaseUserModel.getPurchaseUserListByPurchaseId(corpid, dataId, null);
                for (PurchaseUserEntity entity : purchaseUserEntities) {
                    pushUserList.add(entity.getUserId());
                }
                break;
            case BOMBILL_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.BOMBILL_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.BOMBILL_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(BomPushConstant.BOM_TEAM_ADD_OTHER_CONTENT);
                List<BomUserEntity> bomUserList = bomUserModel.getBomUserListByBomId(corpid, dataId);
                for (BomUserEntity item : bomUserList) {
                    pushUserList.add(item.getUserId());
                }
                break;
            case PRODUCTIONORDER_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.PRODUCTION_ORDER_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.PRODUCTION_ORDER_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(ProductionOrderPushConstant.PRODUCTION_ORDER_TEAM_ADD_OTHER_CONTENT);
                List<ProductionOrderUserEntity> productionOrderUserEntityList = productionOrderUserModel.getProductionOrderUserListByProductionOrderId(corpid, dataId);
                for (ProductionOrderUserEntity item : productionOrderUserEntityList) {
                    pushUserList.add(item.getUserId());
                }
                break;
            case WORK_ORDER_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                businessDataName = businessDataName == null ? userTeamAddPushDTO.getSaveName() : businessDataName;
                pushTypeEnum = PushTypeEnum.WORKORDER_TEAM;
                title = I18nMessageUtil.getMessage(WorkOrderPushConstant.WORK_ORDER_TEAM_ADD_TITLE);
                userContent = I18nMessageUtil.getMessage(WorkOrderPushConstant.TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(WorkOrderPushConstant.TEAM_ADD_OTHER_CONTENT);
                break;
            case QUOTATION_TEAM:
                businessDataName = formDataEntity.getSerialNo();
                pushTypeEnum = isMain ? PushTypeEnum.QUOTATION_TEAM_ADD_DEL_MAIN_PUSH : PushTypeEnum.QUOTATION_TEAM_ADD_DEL_SYNERGETIC_PUSH;
                title = isMain ? I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(QuotationPushConstant.QUOTATAION_TEAM_ADD_OTHER_CONTENT);
                break;
            case CLUE_TEAM:
                businessDataName = FastJsonHelper.getStringOrDefaultFromFormData(formDataEntity.getData(), ClueEnum.COMPANY_NAME.getAttr(), "");
                pushTypeEnum = isMain ? PushTypeEnum.CLUE_TEAM_ADD_DEL_MAIN : PushTypeEnum.CLUE_TEAM_ADD_DEL_SYNERGETIC;
                title = isMain ? I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(CluePushConstant.CLUE_TEAM_ADD_OTHER_CONTENT);
                break;
            case DISTRIBUTOR_TEAM:
                businessDataName = formDataEntity.getData().getString(DistributorEnum.NAME.getAttr());
                pushTypeEnum = isMain ? PushTypeEnum.DISTRIBUTOR_TEAM_ADD_DEL_MAIN : PushTypeEnum.DISTRIBUTOR_TEAM_ADD_DEL_SYNERGETIC;
                title = isMain ? I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_ADD_MAIN_TITLE) : I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_ADD_COLLABORATOR_TITLE);
                userContent = I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_ADD_CONTENT);
                pushContent = I18nMessageUtil.getMessage(DistributorPushConstant.DISTRIBUTOR_TEAM_ADD_OTHER_CONTENT);
                break;
            default:
                break;
        }
        if (Objects.nonNull(pushTypeEnum) && !Objects.equals(userTeamEnum, UserTeamEnum.UNKNOW)) {
            businessType = XbbRefTypeEnum.transferBusinessType2Index(businessType);
            PushSetEntity pushSetEntity = null;
            if (Objects.equals(PushTypeEnum.CUSTOMER_PUSH.getCode(), pushTypeEnum.getCode())) {
                CustomerPushSet customerPushSet = new CustomerPushSet();
                pushSetEntity = customerPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            } else if (Objects.equals(PushTypeEnum.CONTRACT_PUSH.getCode(), pushTypeEnum.getCode())) {
                ContractPushSet contractPushSet = new ContractPushSet();
                pushSetEntity = contractPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            } else if (Objects.equals(PushTypeEnum.ORDER_PUSH.getCode(), pushTypeEnum.getCode())) {
                OrderPushSet orderPushSet = new OrderPushSet();
                pushSetEntity = orderPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            } else if (Objects.equals(PushTypeEnum.OPPORTUNITY_PUSH.getCode(), pushTypeEnum.getCode())) {
                OpportunityPushSet opportunityPushSet = new OpportunityPushSet();
                pushSetEntity = opportunityPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            } else if (Objects.equals(PushTypeEnum.WORKORDER_PUSH.getCode(), pushTypeEnum.getCode())) {
                WorkOrderPushSet workOrderPushSet = new WorkOrderPushSet();
                pushSetEntity = workOrderPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            } else if (Objects.equals(PushTypeEnum.QUOTATION_PUSH.getCode(), pushTypeEnum.getCode())) {
                QuotationPushSet quotationPushSet = new QuotationPushSet();
                pushSetEntity = quotationPushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            } else if (Objects.equals(PushTypeEnum.CLUE_PUSH.getCode(), pushTypeEnum.getCode())) {
                CluePushSet cluePushSet = new CluePushSet();
                pushSetEntity = cluePushSet.getPushSet(corpid, pushTypeEnum.getSubCode(), pushSetModel);
            }
            boolean isEnable = true;
            if (Objects.nonNull(pushSetEntity)) {
                if (Objects.equals(pushSetEntity.getEnable(), 0)) {
                    isEnable = false;
                }
            }

            if (Objects.equals(userTeamEnum, UserTeamEnum.WORK_ORDER_TEAM)) {
                WorkOrderEntity workOrderEntity = new WorkOrderEntity();
                BeanUtil.copyProperties(formDataEntity, workOrderEntity);
                pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, pushTypeEnum.getCode(), pushTypeEnum.getSubCode(), userTeamAddPushDTO.getLoginUser(), workOrderEntity);
            } else if (!Objects.equals(userTeamEnum, UserTeamEnum.SUPPLIER_TEAM) && !Objects.equals(userTeamEnum, UserTeamEnum.BOMBILL_TEAM)
                    && !Objects.equals(userTeamEnum, UserTeamEnum.PRODUCTIONORDER_TEAM) && !Objects.equals(userTeamEnum, UserTeamEnum.PURCHASE_TEAM)) {
                // 从设置中获取推送人员
                pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, pushTypeEnum.getCode(), pushTypeEnum.getSubCode(), userTeamAddPushDTO.getLoginUser(), formDataEntity);
            }
            UserVO loginUser = userTeamAddPushDTO.getLoginUser();
            if (isEnable) {
                // 加入团队的人员的用户id
                List<String> teamUserIds = userTeamAddPushDTO.getUserIdIn();
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(formDataEntity.getAppId(), formDataEntity.getMenuId(), formDataEntity.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), businessType, businessType);
                if (!(teamUserIds.contains(userTeamAddPushDTO.getUserId()) && Objects.equals(teamUserIds.size(), 1))) {
                    if (userTeamEnum.equals(UserTeamEnum.WORK_ORDER_TEAM)) {
                        userContent = String.format(userContent, loginUser.getName(), businessDataName);
                    } else {
                        userContent = String.format(userContent, businessDataName);
                    }
                    teamUserIds.remove(loginUser.getUserId());
                    MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, teamUserIds, Collections.singletonList(dataId), 0, null, title, userContent, null, options);
                    baseProducer.sendMessage(pushTypeEnum, messageRabbitMqDTO);
                }
            }
            if (pushUserList != null && pushUserList.size() > 0) {
                // 加入团队的人员的用户id
                List<String> teamUserIds = userTeamAddPushDTO.getUserIdIn();
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(formDataEntity.getAppId(), formDataEntity.getMenuId(), formDataEntity.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), businessType, businessType);
                Map<String, String> userIdNameMap = userModel.getUserIdNameMap(corpid, teamUserIds);
                StringBuilder teamUserNameSb = new StringBuilder();
                for (String name : userIdNameMap.values()) {
                    teamUserNameSb.append(name).append(StringConstant.COMMA);
                }
                String teamUserName = teamUserNameSb.toString();
                if (StringUtil.isNotEmpty(teamUserName)) {
                    teamUserName = teamUserName.substring(0, teamUserName.length() - 1);
                }
                if (userTeamEnum.equals(UserTeamEnum.WORK_ORDER_TEAM)) {
                    pushContent = String.format(pushContent, loginUser.getName(), teamUserName, businessDataName);
                } else {
                    pushContent = String.format(pushContent, teamUserName, businessDataName);
                }
                //过滤被加的人员
                pushUserList.removeAll(teamUserIds);
                //过滤当前操作人
                pushUserList.remove(loginUser.getUserId());
                MessageRabbitMqDTO messageRabbitMqPushSetDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, title, pushContent, null, options);
                baseProducer.sendMessage(pushTypeEnum, messageRabbitMqPushSetDTO);
            }

        }
    }

    @Override
    public BaseVO createCustomerUser(String corpid, String userId, Long customerId, Integer isMain) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        CustomerUserEntity customerUserEntity = new CustomerUserEntity();
        initEntity(customerUserEntity, userEntity);
        customerUserEntity.setDataId(customerId);
        if (isMain == null) {
            customerUserEntity.setIsMain(MAIN_USER);
        }
        customerUserEntity.setIsMain(isMain);
        customerUserModel.save(customerUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createContractUser(String corpid, String userId, Long contractId, Integer isMain, Long parentId) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        ContractUserEntity contractUserEntity = new ContractUserEntity();
        initEntity(contractUserEntity, userEntity);
        contractUserEntity.setDataId(contractId);
        contractUserEntity.setIsMain(isMain);
        contractUserEntity.setCustomerId(parentId);
        contractUserModel.save(contractUserEntity);
        return new BaseVO();
    }


    @Override
    public BaseVO createQuotationUser(String corpid, String userId, Long quotationId, Integer isMain, Long customerId) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        QuotationUserEntity quotationUserEntity = new QuotationUserEntity();
        initEntity(quotationUserEntity, userEntity);
        quotationUserEntity.setDataId(quotationId);
        quotationUserEntity.setCustomerId(customerId);
        quotationUserEntity.setIsMain(isMain);
        quotationUserModel.save(quotationUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createProductionOrderUser(String corpid, String userId, Long productionOrderId, Integer isMain) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        ProductionOrderUserEntity productionOrderUserEntity = new ProductionOrderUserEntity();
        initEntity(productionOrderUserEntity, userEntity);
        productionOrderUserEntity.setDataId(productionOrderId);
        productionOrderUserEntity.setIsMain(isMain);
        productionOrderUserModel.save(productionOrderUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createPurchaseUser(String corpid, String userId, Long purchaseId, Integer isMain) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        PurchaseUserEntity purchaseUserEntity = new PurchaseUserEntity();
        initEntity(purchaseUserEntity, userEntity);
        purchaseUserEntity.setDataId(purchaseId);
        purchaseUserEntity.setIsMain(isMain);
        purchaseUserModel.save(purchaseUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createContactUser(String corpid, String userId, Long customerId, Long contactId, Integer isMain) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        ContactUserEntity contactUserEntity = new ContactUserEntity();
        initEntity(contactUserEntity, userEntity);
        contactUserEntity.setCustomerId(customerId);
        contactUserEntity.setDataId(contactId);
        contactUserEntity.setIsMain(isMain);
        contactUserModel.save(contactUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createOpportunityUser(String corpid, String userId, Long opportunityId, Integer isMain, Long dataId) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        OpportunityUserEntity opportunityUserEntity = new OpportunityUserEntity();
        initEntity(opportunityUserEntity, userEntity);
        opportunityUserEntity.setDataId(opportunityId);
        opportunityUserEntity.setCustomerId(dataId);
        opportunityUserEntity.setIsMain(isMain);
        opportunityUserModel.save(opportunityUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createSupplierUser(String corpid, String userId, Long supplierId, Integer isMain) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        SupplierUserEntity supplierUserEntity = new SupplierUserEntity();
        initEntity(supplierUserEntity, userEntity);
        supplierUserEntity.setDataId(supplierId);
        supplierUserEntity.setIsMain(isMain);
        supplierUserEntity.setDistributionTime(DateTimeUtil.getInt());
        supplierUserModel.save(supplierUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createBomBillUser(String corpid, String userId, Long bomBillId, Integer isMain) throws XbbException {
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        BomUserEntity bomUserEntity = new BomUserEntity();
        initEntity(bomUserEntity, userEntity);
        bomUserEntity.setDataId(bomBillId);
        bomUserEntity.setIsMain(isMain);
        bomUserModel.save(bomUserEntity);
        return new BaseVO();
    }

    @Override
    public BaseVO createPaymentUser(String corpid, Long customerId, Long contractId, List<Long> paymentIdIn, Integer paymentLinkType, Boolean parentNew) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",DelEnum.NORMAL.getDel());
//        map.put("dataIdIn",paymentIdIn);
        List<UserTeamEntity> userTeamEntityList;
        if (parentNew){
            map.put("customerId",customerId);
            userTeamEntityList = customerUserModel.findBaseEntitys(map);
        }else {
            map.put("contractId",contractId);
            userTeamEntityList = contractUserModel.findBaseEntitys(map);
        }

        List<PaymentUserEntity> paymentUserEntityList = new ArrayList<>();
        for (Long paymentId : paymentIdIn) {
            for (UserTeamEntity entity : userTeamEntityList) {
                PaymentUserEntity paymentUserEntity = new PaymentUserEntity();
                BeanUtil.copyProperties(entity, paymentUserEntity);
                paymentUserEntity.setId(null);
                paymentUserEntity.setDataId(paymentId);
                paymentUserEntity.setCustomerId(customerId);
                paymentUserEntity.setContractId(contractId);
                paymentUserEntity.setRefType(paymentLinkType);
                paymentUserEntityList.add(paymentUserEntity);
            }
        }
        if (!paymentUserEntityList.isEmpty()){
            paymentUserModel.insertBatch(paymentUserEntityList);
        }
        return new BaseVO();
    }

    @Override
    public BaseVO createPayPlanUser(String corpid, Long supplierId, Long purchaseId, List<Long> payPlanIdIn, boolean parentNew) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",DelEnum.NORMAL.getDel());
        List<UserTeamEntity> userTeamEntityList;
        if (parentNew){
            map.put("supplierId",supplierId);
            userTeamEntityList = supplierUserModel.findBaseEntitys(map);
        }else {
            map.put("purchaseId",purchaseId);
            userTeamEntityList = purchaseUserModel.findBaseEntitys(map);
        }
        List<PayPlanUserEntity> payPlanUserEntityList = new ArrayList<>();
        for (Long payPlanId : payPlanIdIn) {
            for (UserTeamEntity entity : userTeamEntityList) {
                PayPlanUserEntity payPlanUserEntity = new PayPlanUserEntity();
                BeanUtil.copyProperties(entity, payPlanUserEntity);
                payPlanUserEntity.setId(null);
                payPlanUserEntity.setDataId(payPlanId);
                payPlanUserEntity.setSupplierId(supplierId);
                payPlanUserEntity.setPurchaseId(purchaseId);
                payPlanUserEntityList.add(payPlanUserEntity);
            }
        }
        if (!payPlanUserEntityList.isEmpty()) {
            payPlanUserModel.insertBatch(payPlanUserEntityList);
        }

        return new BaseVO();
    }

    /**
     *
     * @param corpid 公司编号
     * @param customerId 客户编号
     * @param contractIdIn 合同编号
     * @param sheetIdAndDataIdMap <回款单款单编号,合同编号/客户编号>
     * @param sheetTypeEnum 回款单类型
     * @param parentNew 合同是否新建
     * @return
     * @throws XbbException
     */
    @Override
    public BaseVO createPaymentSheetUser(String corpid, Long customerId, List<Long> contractIdIn, Map<Long, List<Long>> sheetIdAndDataIdMap, SheetTypeEnum sheetTypeEnum, Boolean parentNew) throws XbbException {
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        map.put("del", DelEnum.NORMAL.getDel());
        List<UserTeamEntity> userTeamList;
        if ( SheetTypeEnum.noBelong(sheetTypeEnum) || parentNew) {
            map.put("customerId", customerId);
            userTeamList = customerUserModel.findBaseEntitys(map);
        } else {
            map.put("contractIdIn", contractIdIn);
            userTeamList = contractUserModel.findBaseEntitys(map);
        }
        Map<Long,UserTypePojo> paySheetIdMap = getSetUserTeamEntityMap(userTeamList,sheetIdAndDataIdMap);

        if (  !paySheetIdMap.isEmpty()) {
            List<PaymentSheetUserEntity> paymentSheetUserEntityList = new ArrayList<>();
            for ( Map.Entry<Long, UserTypePojo> sheetIdAndUser : paySheetIdMap.entrySet() ) {
                Long paymentSheetId = sheetIdAndUser.getKey();
                UserTypePojo userTypePojo = sheetIdAndUser.getValue();
                if ( Objects.nonNull(userTypePojo.getMainUserList()) ) {
                    for ( UserTeamEntity entity : userTypePojo.getMainUserList() ) {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(entity, paymentSheetUserEntity);
                        paymentSheetUserEntity.setId(null);
                        paymentSheetUserEntity.setIsMain(BasicConstant.MAIN_USER);
                        paymentSheetUserEntity.setDataId(paymentSheetId);
                        paymentSheetUserEntityList.add(paymentSheetUserEntity);
                    }
                }
                if ( Objects.nonNull(userTypePojo.getCoorUserList()) ) {
                    for ( UserTeamEntity entity : userTypePojo.getCoorUserList() ) {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(entity, paymentSheetUserEntity);
                        paymentSheetUserEntity.setId(null);
                        paymentSheetUserEntity.setIsMain(BasicConstant.COOP_USER);
                        paymentSheetUserEntity.setDataId(paymentSheetId);
                        paymentSheetUserEntityList.add(paymentSheetUserEntity);
                    }
                }
            }
            if ( !paymentSheetUserEntityList.isEmpty() ) {
                paymentSheetUserModel.insertBatch(paymentSheetUserEntityList);
            }
        }
        return new BaseVO();
    }

    private Map<Long, UserTypePojo> getSetUserTeamEntityMap(List<UserTeamEntity> userTeamEntityList, Map<Long, List<Long>> sheetIdAndDataIdMap ){
        Map<Long, UserTypePojo> dataIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (UserTeamEntity userTeamEntity : userTeamEntityList) {
            UserTypePojo userTypePojo = dataIdMap.get(userTeamEntity.getDataId())!=null?dataIdMap.get(userTeamEntity.getDataId()):new UserTypePojo();
            if ( Objects.equals(userTeamEntity.getIsMain(),BasicConstant.MAIN_USER) ){
                userTypePojo.getMainUserList().add(userTeamEntity);
            } else {
                userTypePojo.getCoorUserList().add(userTeamEntity);
            }
            dataIdMap.put(userTeamEntity.getDataId(),userTypePojo);
        }
        Map<Long,UserTypePojo> paySheetIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //todo chenshan需要处理一下在不同合同人上即时负责人又是协同人
        for ( Map.Entry<Long, List<Long>> sheetIdAndDataId : sheetIdAndDataIdMap.entrySet() ) {
            List<Long> dataIds = sheetIdAndDataId.getValue();
            Long paySheetId = sheetIdAndDataId.getKey();
            UserTypePojo newUserTypePojo = new UserTypePojo();
            List<UserTeamEntity> newMainUserList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<UserTeamEntity> newCoorUserList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<String> userIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for ( Long dataId : dataIds ) {
                UserTypePojo userTypePojo = dataIdMap.get(dataId);
                if ( Objects.nonNull(userTypePojo) ) {
                    List<UserTeamEntity> mainUserList = userTypePojo.getMainUserList();
                    List<UserTeamEntity> coorUserList = userTypePojo.getCoorUserList();
                    for ( UserTeamEntity userTeamEntity : mainUserList ) {
                        if ( !userIdIn.contains(userTeamEntity.getUserId()) ) {
                            newMainUserList.add(userTeamEntity);
                            userIdIn.add(userTeamEntity.getUserId());
                        }
                    }
                    for ( UserTeamEntity userTeamEntity : coorUserList ) {
                        if ( !userIdIn.contains(userTeamEntity.getUserId()) ) {
                            newCoorUserList.add(userTeamEntity);
                        }
                    }
                }
            }
            newUserTypePojo.setMainUserList(newMainUserList);
            newUserTypePojo.setCoorUserList(newCoorUserList);
            paySheetIdMap.put(paySheetId, newUserTypePojo);
        }
        return paySheetIdMap;
    }

    /**
     *
     * @param corpid 公司编号
     * @param supplierId 供应商编号
     * @param purchaseIdIn 采购合同编号
     * @param sheetIdAndDataIdMap <付款单编号,采购合同/供应商编号>
     * @param sheetTypeEnum 付款单类型
     * @param parentNew 采购合同是否新建
     * @return
     * @throws XbbException
     */
    @Override
    public BaseVO createPaySheetUser(String corpid, Long supplierId, List<Long> purchaseIdIn, Map<Long, List<Long>> sheetIdAndDataIdMap,  SheetTypeEnum sheetTypeEnum, Boolean parentNew) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",DelEnum.NORMAL.getDel());
        List<UserTeamEntity> userTeamEntityList;
        if ( SheetTypeEnum.noBelong(sheetTypeEnum) || parentNew) {
            map.put("supplierId",supplierId);
            userTeamEntityList = supplierUserModel.findBaseEntitys(map);
        }else {
            map.put("purchaseIdIn",purchaseIdIn);
            userTeamEntityList = purchaseUserModel.findBaseEntitys(map);
        }
        Map<Long,UserTypePojo> paySheetIdMap = getSetUserTeamEntityMap(userTeamEntityList,sheetIdAndDataIdMap);
        if (  !paySheetIdMap.isEmpty()) {
            List<PayPlanSheetUserEntity> payPlanSheetUserEntityList = new ArrayList<>();
            for ( Map.Entry<Long, UserTypePojo> sheetIdAndUser : paySheetIdMap.entrySet() ) {
                Long paySheetId = sheetIdAndUser.getKey();
                UserTypePojo userTypePojo = sheetIdAndUser.getValue();
                if ( Objects.nonNull(userTypePojo.getMainUserList()) ) {
                    for ( UserTeamEntity entity : userTypePojo.getMainUserList() ) {
                        PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                        BeanUtil.copyProperties(entity, payPlanSheetUserEntity);
                        payPlanSheetUserEntity.setId(null);
                        payPlanSheetUserEntity.setIsMain(BasicConstant.MAIN_USER);
                        payPlanSheetUserEntity.setDataId(paySheetId);
                        payPlanSheetUserEntityList.add(payPlanSheetUserEntity);
                    }
                }
                if ( Objects.nonNull(userTypePojo.getCoorUserList()) ) {
                    for ( UserTeamEntity entity : userTypePojo.getCoorUserList() ) {
                        PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                        BeanUtil.copyProperties(entity, payPlanSheetUserEntity);
                        payPlanSheetUserEntity.setId(null);
                        payPlanSheetUserEntity.setIsMain(BasicConstant.COOP_USER);
                        payPlanSheetUserEntity.setDataId(paySheetId);
                        payPlanSheetUserEntityList.add(payPlanSheetUserEntity);
                    }
                }
            }
            if (!payPlanSheetUserEntityList.isEmpty()) {
                payPlanSheetUserModel.insertBatch(payPlanSheetUserEntityList);
            }
        }
        return new BaseVO();
    }

    @Override
    public BaseVO createSupplierContactUser(String corpid, Long supplierId, List<Long> contactIdIn) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("supplierId",supplierId);
        map.put("del",DelEnum.NORMAL.getDel());
        List<SupplierUserEntity> supplierUserEntityList = supplierUserModel.findEntitys(map);
        List<SupplierContactUserEntity> supplierContactUserEntityList = new ArrayList<>();
        for (Long contactId : contactIdIn) {
            for (SupplierUserEntity entity : supplierUserEntityList) {
                SupplierContactUserEntity supplierContactUserEntity = new SupplierContactUserEntity();
                BeanUtil.copyProperties(entity, supplierContactUserEntity);
                supplierContactUserEntity.setId(null);
                supplierContactUserEntity.setSupplierId(supplierId);
                supplierContactUserEntity.setDataId(contactId);
                supplierContactUserEntity.setSupplierId(entity.getDataId());
                supplierContactUserEntityList.add(supplierContactUserEntity);
            }
        }
        supplierContactUserModel.insetBatch(supplierContactUserEntityList);
        return new BaseVO();
    }

    @Override
    public void getUserIdMap(List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Map<Long, List<String>> mainUserIdMap, Map<Long, List<String>> coUserIdMap) {
        formDataFormExplainHelper.getUserIdMap(dataIdList, corpid, businessType, isPublic, mainUserIdMap, coUserIdMap);
    }

    /**
     *
     * @param dataIdList 业务数据idList
     * @param corpid 公司id
     * @param businessType
     * @param isPublic 是否公海(有个前负责人逻辑
     * @param mainUserIdMap
     * @param coUserIdMap
     */
    @Override
    public void getAnotherUserIdMap(List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Map<Long, List<String>> mainUserIdMap, Map<Long, List<String>> coUserIdMap) {
        List<UserTeamEntity> userTeamEntityList = businessUserTeamHelp.getUserTeamList(dataIdList, corpid, businessType, isPublic);
        for (UserTeamEntity entity : userTeamEntityList) {
            //仓库团队表中没有isMain标识，没有协同人，所以查出来的都是负责人
            if (Objects.equals(entity.getIsMain(),1) || Objects.equals(businessType,XbbRefTypeEnum.WAREHOUSE.getCode())){
                if (mainUserIdMap.containsKey(entity.getDataId())) {
                    List<String> userId =  mainUserIdMap.get(entity.getDataId());
                    userId.add(entity.getUserId());
                    mainUserIdMap.put(entity.getDataId(), userId);
                } else {
                    List<String> userId = new ArrayList<>();
                    userId.add(entity.getUserId());
                    mainUserIdMap.put(entity.getDataId(), userId);
                }

            }else {
                if (coUserIdMap.containsKey(entity.getDataId())) {
                    List<String> userId =  coUserIdMap.get(entity.getDataId());
                    userId.add(entity.getUserId());
                    coUserIdMap.put(entity.getDataId(), userId);
                }else {
                    List<String> userId = new ArrayList<>();
                    userId.add(entity.getUserId());
                    coUserIdMap.put(entity.getDataId(), userId);
                }
            }
        }
    }

    @Override
    public void getUserIdMapSetShow( Set<String> userIdList,List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Map<Long, List<String>> mainUserIdMap, Map<Long, List<String>> coUserIdMap) {
        businessUserTeamHelp.getUserIdMapSetShow(userIdList, dataIdList, corpid, businessType, isPublic, mainUserIdMap, coUserIdMap, DelEnum.NORMAL.getDel());
    }

    @Override
    public void verifyMyTeamForImport(VerifyUserTeamForImportDTO verifyUserTeamForImportDTO) throws XbbException{
        // 新的负责人
        List<String> newMainUserList = new ArrayList<>();
        if (verifyUserTeamForImportDTO.getOwnerId() != null) {
            for (int i = 0; i < verifyUserTeamForImportDTO.getOwnerId().size(); i++) {
                newMainUserList.add(Objects.toString(verifyUserTeamForImportDTO.getOwnerId().get(i).getId(), ""));
            }
        }
        // 新的协同人
        List<String> newCoUserList = new ArrayList<>();
        if (verifyUserTeamForImportDTO.getCoUserId() != null) {
            verifyUserTeamForImportDTO.getCoUserId().forEach(coUser-> newCoUserList.add(Objects.toString(coUser.getId(), "")));
        }
        List<String> copyNewMainUserList = (List<String>)CloneUtil.deepClone(newMainUserList);
        copyNewMainUserList.retainAll(newCoUserList);
        if (CollectionsUtil.isNotEmpty(copyNewMainUserList)) {
            List<UserEntity> userList = userModel.getByUserIdIn(verifyUserTeamForImportDTO.getCorpid(), newMainUserList, true);
            StringBuilder errorUserName = new StringBuilder();
            String errorUser = "";
            for (UserEntity userEntity : userList) {
                errorUserName.append(userEntity.getName()).append(StringConstant.COMMA);
            }
            if (!errorUserName.toString().isEmpty()) {
                errorUser = errorUserName.substring(0, errorUserName.length() - 1);
            }
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200024, String.format(BuinessDefaultErrorCodeEnum.API_ERROR_200024.getMsg(), errorUser));
        }
        // 判断权限的DTO
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(verifyUserTeamForImportDTO, handlerExplainDTO);
        handlerExplainDTO.setCreatorId(verifyUserTeamForImportDTO.getCreatorId());
        // 获取协同人和负责人的解释
        Map<String, FieldAttrEntity> explainMap = verifyUserTeamForImportDTO.getExplainMap();
        FieldAttrEntity ownerField = explainMap.getOrDefault(FieldTypeEnum.OWNERID.getAlias(), new FieldAttrEntity());
        FieldAttrEntity coUserField = explainMap.getOrDefault(FieldTypeEnum.COUSERID.getAlias(), new FieldAttrEntity());
        // 是否有添加权限
        Boolean haveMainAddPermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
        Boolean haveCoUserAddPermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
        if (!newMainUserList.isEmpty()) {
            if (!haveMainAddPermission) {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007);
            }
        }
        if (!newCoUserList.isEmpty()) {
            if (!haveCoUserAddPermission) {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390008);
            }
        }
    }

    @Override
    public void batchGetUserTeamMap(List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Map<Long, List<UserTeamEntity>> mainUserMap, Map<Long, List<UserTeamEntity>> coUserMap) {
        List<UserTeamEntity> userTeamEntityList = businessUserTeamHelp.getUserTeamList(dataIdList, corpid, businessType, isPublic);
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(ParameterConstant.CORPID, corpid);
        map.put(ParameterConstant.DEL, DelEnum.DELETE.getDel());
        List<UserEntity> delUser = userModel.findEntitys(map);
        List<String> delUserIdList = new ArrayList<>();
        delUser.forEach(userEntity -> delUserIdList.add(userEntity.getUserId()));
        for (UserTeamEntity entity : userTeamEntityList) {
            String name = "";
            if (Objects.equals(entity.getIsMain(),1)){
                if (mainUserMap.containsKey(entity.getDataId())) {
                    List<UserTeamEntity> teamEntityList =  mainUserMap.get(entity.getDataId());
                    teamEntityList.add(entity);
                    mainUserMap.put(entity.getDataId(), teamEntityList);
                } else {
                    List<UserTeamEntity> teamEntityList = new ArrayList<>();
                    teamEntityList.add(entity);
                    mainUserMap.put(entity.getDataId(), teamEntityList);
                }
            }else {
                if (coUserMap.containsKey(entity.getDataId())) {
                    List<UserTeamEntity> teamEntityList =  coUserMap.get(entity.getDataId());
                    teamEntityList.add(entity);
                    coUserMap.put(entity.getDataId(), teamEntityList);
                }else {
                    List<UserTeamEntity> teamEntityList = new ArrayList<>();
                    teamEntityList.add(entity);
                    coUserMap.put(entity.getDataId(), teamEntityList);
                }
            }
        }
    }

    @Override
    public void saveMyTeam(UserTeamBatchSaveDTO userTeamBatchSaveDTO) throws XbbException {
        List<UserTeamBatchAddDTO> userTeamBatchAddDTOList = userTeamBatchSaveDTO.getUserTeamBatchAddDTOList();
        List<UserTeamBatchDeleteDTO> userTeamBatchDeleteDTOList = userTeamBatchSaveDTO.getUserTeamBatchDeleteDTOList();
        List<UserTeamBatchUpdateDTO> userTeamBatchUpdateDTOList = userTeamBatchSaveDTO.getUserTeamBatchUpdateDTOList();
        // 日志
        String loginUserName = userTeamBatchSaveDTO.getLoginUserName();
        String corpid = userTeamBatchSaveDTO.getCorpid();
        String userId = userTeamBatchSaveDTO.getUserId();
        Integer businessType = userTeamBatchSaveDTO.getBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(XbbRefTypeEnum.transferBusinessType4Distributor(businessType,userTeamBatchSaveDTO.getDistributorMark()));
        if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.UNKNOWN)) {
            throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        String xbbRefTypeName = xbbRefTypeEnum.getName();
        String saveName = getSaveName(userTeamBatchSaveDTO);
        //回款单/付款单的团队逻辑添加跟其他不同，需要特殊处理
        if ( (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT, xbbRefTypeEnum)
                || Objects.equals(XbbRefTypeEnum.CONTRACT, xbbRefTypeEnum)
                || Objects.equals(XbbRefTypeEnum.SUPPLIER, xbbRefTypeEnum)
                || Objects.equals(XbbRefTypeEnum.PURCHASE, xbbRefTypeEnum)
                || Objects.equals(XbbRefTypeEnum.ORDER, xbbRefTypeEnum)
                || Objects.equals(XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT, xbbRefTypeEnum))
                && (CollectionsUtil.isNotEmpty(userTeamBatchAddDTOList)
                || CollectionsUtil.isNotEmpty(userTeamBatchDeleteDTOList)
                || CollectionsUtil.isNotEmpty(userTeamBatchUpdateDTOList)) ) {
            Boolean isNew = userTeamBatchSaveDTO.getIsCustomerNew() == null ? false : userTeamBatchSaveDTO.getIsCustomerNew();
            if (!isNew) {
                updateSheetTeam(corpid,xbbRefTypeEnum,userTeamBatchSaveDTO.getDataId());
            }
        }
        if (CollectionsUtil.isNotEmpty(userTeamBatchAddDTOList)) {
            for (UserTeamBatchAddDTO userTeamBatchAddDTO : userTeamBatchAddDTOList) {
                userTeamBatchAddDTO.setIsCustomerNew(userTeamBatchSaveDTO.getIsCustomerNew());
                batchAddMainUser(userTeamBatchAddDTO);
            }


            Runnable runnable = () -> {
                try {
                    String memo;
                    for(UserTeamBatchAddDTO userTeamBatchAddDTO : userTeamBatchAddDTOList){
                        // 消息推送
                        UserTeamAddPushDTO userTeamAddPushDTO = new UserTeamAddPushDTO();
                        BeanUtil.copyProperties(userTeamBatchAddDTO, userTeamAddPushDTO);
                        userTeamAddPushDTO.setLoginUser(userTeamBatchSaveDTO.getLoginUser());
                        userTeamAddPushDTO.setSaveName(saveName);
                        pushMessageAfterAddUser(userTeamAddPushDTO);

                        // 日志处理
                        String isMainStr = Objects.equals(userTeamBatchAddDTO.getIsMain(), 1) ? I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS) : I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
                        OperateModuleTypeEnum operateModuleTypeEnum = Objects.equals(userTeamBatchAddDTO.getIsMain(), 1) ? OperateModuleTypeEnum.RESPONSIBLE_TEAM : OperateModuleTypeEnum.COLLABORATIVE_TEAM;
                        List<String> userIdIn = userTeamBatchAddDTO.getUserIdIn();
                        List<UserEntity> userList = userModel.getByUserId(userIdIn, corpid);
                        List<String> userNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        userList.forEach(user -> userNameList.add(user.getName()));
                        String userNameListStr = StringUtils.join(userNameList, "，");

                        if(userList.size() > 1){
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_ADD_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr);
                            List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            InfoArrPojo infoArrPojo = new InfoArrPojo();
                            infoArrPojo.setTitle(isMainStr);
                            infoArrPojo.setContent(userNameListStr);
                            infoArrPojoList.add(infoArrPojo);
                            mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.NEW,
                                    "", "", memo, userTeamBatchSaveDTO.getHttpHeader());
                        } else if(Objects.equals(userList.size(), 1)){
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr, userNameListStr);
                            mongoLogHelp.buildLogWithoutAsync(corpid, userId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.NEW,
                                    userList.get(0).toString(), userNameListStr, memo, userTeamBatchSaveDTO.getHttpHeader());
                        }
                    }
                } catch (Exception e) {
                    LOG.error("com.xbongbong.saas.service.impl.UserTeamServiceImpl.saveMyTeam log error", e);
                }

            };
            logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        }
        if (CollectionsUtil.isNotEmpty(userTeamBatchUpdateDTOList)) {
            for (UserTeamBatchUpdateDTO userTeamBatchUpdateDTO : userTeamBatchUpdateDTOList) {
                batchUpdateUserTeam(userTeamBatchUpdateDTO);
            }


            Runnable runnable = () -> {
                try {
                    String memo;
                    for (UserTeamBatchUpdateDTO userTeamBatchUpdateDTO : userTeamBatchUpdateDTOList) {
                        String isMainStr = Objects.equals(userTeamBatchUpdateDTO.getIsMain(), 1) ? I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS) : I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
                        OperateModuleTypeEnum operateModuleTypeEnum = Objects.equals(userTeamBatchUpdateDTO.getIsMain(), 1) ? OperateModuleTypeEnum.RESPONSIBLE_TEAM : OperateModuleTypeEnum.COLLABORATIVE_TEAM;
                        List<String> userIdIn = userTeamBatchUpdateDTO.getUpdateUserIdIn();
                        List<UserEntity> userList = userModel.getByUserId(userIdIn, corpid);
                        List<String> userNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        userList.forEach(user -> userNameList.add(user.getName()));
                        String userNameListStr = StringUtils.join(userNameList, "，");

                        if(userList.size() > 1){
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr);
                            List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            InfoArrPojo infoArrPojo = new InfoArrPojo();
                            infoArrPojo.setTitle(isMainStr);
                            infoArrPojo.setContent(userNameListStr);
                            infoArrPojoList.add(infoArrPojo);
                            mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.EDIT,
                                    "", "", memo, userTeamBatchSaveDTO.getHttpHeader());
                        } else if(Objects.equals(userList.size(), 1)){
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr, userNameListStr);
                            mongoLogHelp.buildLogWithoutAsync(corpid, userId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.EDIT,
                                    userList.get(0).toString(), userNameListStr, memo, userTeamBatchSaveDTO.getHttpHeader());
                        }
                    }
                } catch (Exception e) {
                    LOG.error("com.xbongbong.saas.service.impl.UserTeamServiceImpl.saveMyTeam log error", e);
                }
            };
            logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);



        }
        if (CollectionsUtil.isNotEmpty(userTeamBatchDeleteDTOList)) {
            for (UserTeamBatchDeleteDTO userTeamBatchDeleteDTO : userTeamBatchDeleteDTOList) {
                batchDeleteUserTeam(userTeamBatchDeleteDTO);
            }

            Runnable runnable = () -> {
              try {
                  String memo;
                  for (UserTeamBatchDeleteDTO userTeamBatchDeleteDTO : userTeamBatchDeleteDTOList) {
                      // 消息推送
                      UserTeamDelPushDTO userTeamDelPushDTO = new UserTeamDelPushDTO();
                      BeanUtil.copyProperties(userTeamBatchDeleteDTO, userTeamDelPushDTO);
                      userTeamDelPushDTO.setDataId(userTeamBatchDeleteDTO.getOtherId());
                      pushMessageAfterRemoveUser(userTeamDelPushDTO);

                      // 日志处理
                      String isMainStr = Objects.equals(userTeamBatchDeleteDTO.getIsMain(), 1) ? I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS) : I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
                      OperateModuleTypeEnum operateModuleTypeEnum = Objects.equals(userTeamBatchDeleteDTO.getIsMain(), 1) ? OperateModuleTypeEnum.RESPONSIBLE_TEAM : OperateModuleTypeEnum.COLLABORATIVE_TEAM;
                      List<String> userIdIn = userTeamBatchDeleteDTO.getUpdateUserIdIn();
                      List<UserEntity> userList = userModel.getByUserId(userIdIn, corpid);
                      List<String> userNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                      userList.forEach(user -> userNameList.add(user.getName()));
                      String userNameListStr = StringUtils.join(userNameList, "，");

                      if(userList.size() > 1){
                          memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DEL_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr);
                          List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                          InfoArrPojo infoArrPojo = new InfoArrPojo();
                          infoArrPojo.setTitle(isMainStr);
                          infoArrPojo.setContent(userNameListStr);
                          infoArrPojoList.add(infoArrPojo);
                          mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.DELETE,
                                  "", "", memo, userTeamBatchSaveDTO.getHttpHeader());
                      } else if(Objects.equals(userList.size(), 1)){
                          memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DEL_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr, userNameListStr);
                          mongoLogHelp.buildLogWithoutAsync(corpid, userId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.DELETE,
                                  userList.get(0).toString(), userNameListStr, memo, userTeamBatchSaveDTO.getHttpHeader());
                      }
                  }
              } catch (Exception e) {
                  LOG.error("com.xbongbong.saas.service.impl.UserTeamServiceImpl.saveMyTeam log error", e);
              }
            };
            logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        }
    }

    /**
     * 根据不同类型，需要用不同的参数更新团队数据
     * @param corpid
     * @param xbbRefTypeEnum
     * @param dataId
     * @throws XbbException
     */
    @Override
    public void updateSheetTeam(String corpid, XbbRefTypeEnum xbbRefTypeEnum, Long dataId) throws XbbException{
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
            case DISTRIBUTOR_MANAGEMENT:
                queryUserTeamBySheetBusiness(corpid,dataId,xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET,PaymentSheetEnum.CUSTOMER_ID.getAttr());
                break;
            case CONTRACT:
            case ORDER:
                queryUserTeamBySheetBusiness(corpid,dataId,xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET,PaymentSheetEnum.CONTRACT.getAttr());
                break;
            case SUPPLIER:
                queryUserTeamBySheetBusiness(corpid,dataId,xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET,PaySheetEnum.LINK_SUPPLIER.getAttr());
                break;
            case PURCHASE:
                queryUserTeamBySheetBusiness(corpid,dataId,xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET,PaySheetEnum.LINK_PURCHASE.getAttr());
                break;
            default:
                break;
        }
    }

    /**
     * 先查出关联业务的团队(合同/客户、采购合同/供应商)进行去重后，在根据回款单/付款单的负责团队去重之后，由两者进行对比后得出最后的结论
     * @param corpid
     * @param otherId
     * @param fromBusinessTypeEnum
     * @param businessTypeEnum
     * @param relyAttr
     * @throws XbbException
     */
    private void queryUserTeamBySheetBusiness(String corpid, Long otherId,  XbbRefTypeEnum fromBusinessTypeEnum, XbbRefTypeEnum businessTypeEnum, String relyAttr) throws XbbException {
        Integer businessType = businessTypeEnum.getCode();
        //查出所有的回款单/付款单数据
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        List<String> fieldList = new ArrayList<>();
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        List<Long> otherBusinessIdIn = new ArrayList<>();
        switch (businessTypeEnum) {
            case PAYMENT_SHEET:
                if (Objects.equals(PaymentSheetEnum.CUSTOMER_ID.getAttr(), relyAttr)) {
                    boolQueryBuilder.filter(termQuery("data." + relyAttr + ".keyword", otherId.toString()));
                    fieldList.add(PaymentSheetEnum.getAttrConnectData(PaymentSheetEnum.CUSTOMER_ID));
                    boolQueryBuilder.filter(termsQuery(PaymentSheetEnum.getEsAttr4Keyword(PaymentSheetEnum.PAYMENT_SHEET_TYPE), SheetTypeEnum.belongPrepay(XbbRefTypeEnum.PAYMENT_SHEET)));
                } else {
                    boolQueryBuilder.filter(matchPhraseQuery("data." + relyAttr,otherId.toString()));
                    fieldList.add(PaymentSheetEnum.getAttrConnectData(PaymentSheetEnum.CONTRACT));
                    boolQueryBuilder.filter(termsQuery(PaymentSheetEnum.getEsAttr4Keyword(PaymentSheetEnum.PAYMENT_SHEET_TYPE), SheetTypeEnum.belongOther(XbbRefTypeEnum.PAYMENT_SHEET)));
                }
                break;
            case PAY_SHEET:
                if (Objects.equals(PaySheetEnum.LINK_SUPPLIER.getAttr(), relyAttr)) {
                    boolQueryBuilder.filter(termQuery("data." + relyAttr + ".keyword", otherId.toString()));
                    fieldList.add(PaySheetEnum.getAttrConnectData(PaySheetEnum.LINK_SUPPLIER));
                    boolQueryBuilder.filter(termsQuery(PaySheetEnum.getEsAttr4Keyword(PaySheetEnum.PAY_SHEET_TYPE), SheetTypeEnum.belongPrepay(XbbRefTypeEnum.PAY_SHEET)));
                } else {
                    boolQueryBuilder.filter(matchPhraseQuery("data." + relyAttr,otherId.toString()));
                    fieldList.add(PaySheetEnum.getAttrConnectData(PaySheetEnum.LINK_PURCHASE));
                    boolQueryBuilder.filter(termsQuery(PaySheetEnum.getEsAttr4Keyword(PaySheetEnum.PAY_SHEET_TYPE), SheetTypeEnum.belongOther(XbbRefTypeEnum.PAY_SHEET)));
                }
                break;
            default:
                break;
        }
        fieldList.add(FieldTypeEnum.DATAID.getAlias());
        List<PaasFormDataEntityExt> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        Map<Long, List<Long>> sheetIdAndDataIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> replyDataIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        switch (fromBusinessTypeEnum) {
            case CUSTOMER_MANAGEMENT:
            case DISTRIBUTOR_MANAGEMENT:
                for ( PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataList ) {
                    List<Long> dataIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Long dataId = paasFormDataEntityExt.getDataId();
                    otherBusinessIdIn.add(dataId);
                    JSONObject data = paasFormDataEntityExt.getData();
                    Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data,PaymentSheetEnum.CUSTOMER_ID.getAttr(),0L);
                    replyDataIds.add(customerId);
                    dataIds.add(customerId);
                    sheetIdAndDataIdMap.put(dataId,dataIds);
                }
                break;
            case CONTRACT:
            case ORDER:
                for ( PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataList ) {
                    List<Long> dataIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Long dataId = paasFormDataEntityExt.getDataId();
                    otherBusinessIdIn.add(dataId);
                    JSONObject data = paasFormDataEntityExt.getData();
                    JSONArray contractIdArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data,PaymentSheetEnum.CONTRACT.getAttr(),new JSONArray());
                    for ( Object contractIdObj : contractIdArr ) {
                        if ( Objects.nonNull(contractIdObj) ) {
                            dataIds.add(Long.valueOf(contractIdObj.toString()));
                            replyDataIds.add(Long.valueOf(contractIdObj.toString()));
                        }
                    }
                    sheetIdAndDataIdMap.put(dataId,dataIds);
                }
                break;
            case SUPPLIER:
                for ( PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataList ) {
                    List<Long> dataIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Long dataId = paasFormDataEntityExt.getDataId();
                    otherBusinessIdIn.add(dataId);
                    JSONObject data = paasFormDataEntityExt.getData();
                    Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(data,PaySheetEnum.LINK_SUPPLIER.getAttr(),0L);
                    replyDataIds.add(supplierId);
                    dataIds.add(supplierId);
                    sheetIdAndDataIdMap.put(dataId,dataIds);
                }
                break;
            case PURCHASE:
                for ( PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataList ) {
                    List<Long> dataIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Long dataId = paasFormDataEntityExt.getDataId();
                    otherBusinessIdIn.add(dataId);
                    JSONObject data = paasFormDataEntityExt.getData();
                    JSONArray purchaseIdArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data,PaySheetEnum.LINK_PURCHASE.getAttr(),new JSONArray());
                    for ( Object purchaseIdObj : purchaseIdArr ) {
                        if ( Objects.nonNull(purchaseIdObj) ) {
                            dataIds.add(Long.valueOf(purchaseIdObj.toString()));
                            replyDataIds.add(Long.valueOf(purchaseIdObj.toString()));
                        }
                    }
                    sheetIdAndDataIdMap.put(dataId,dataIds);
                }
                break;
            default:
                break;
        }
        if ( otherBusinessIdIn.isEmpty() || replyDataIds.isEmpty() ) {
            return;
        }
        //取到所有本次相关数据(合同/客户、采购合同/供应商)的团队负责人,数据源团队
        IndexTypeEnum teamIndexTypeEnum = indexTypeModel.getTeamIndexType(corpid, fromBusinessTypeEnum.getCode());

        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexTypeEnum, StringConstant.DATA_ID), replyDataIds));
        List<PaasFormDataEntity> sourceUserTeams = esHelper.findByScroll(teamIndexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> sourceTeamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexTypeEnum, sourceUserTeams);
        //回款单/付款单id，下关联的合同/客户、采购合同/供应商的负责人/协同人
        Map<Long, UserTypePojo> sourceDataIdMap = getSetUserTeamEntityMap(sourceTeamEntityList,sheetIdAndDataIdMap);
        //回款单/付款单现有的团队
        IndexTypeEnum userTeamIndex = indexTypeModel.getTeamIndexType(corpid, businessType);

        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(userTeamIndex, StringConstant.DATA_ID), otherBusinessIdIn));
        List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(userTeamIndex, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(userTeamIndex, userTeamList);
        Map<Long, UserTypePojo> oldDataIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for ( UserTeamEntity userTeamEntity : teamEntityList) {
            UserTypePojo userTypePojo = oldDataIdMap.get(userTeamEntity.getDataId()) ==null? new UserTypePojo(): oldDataIdMap.get(userTeamEntity.getDataId());
            if ( Objects.equals(userTeamEntity.getIsMain(),BasicConstant.MAIN_USER) ) {
                userTypePojo.getMainUserList().add(userTeamEntity);
                userTypePojo.getOldMainUserMap().put(userTeamEntity.getUserId(), userTeamEntity);
            } else {
                userTypePojo.getCoorUserList().add(userTeamEntity);
                userTypePojo.getOldCoorUserMap().put(userTeamEntity.getUserId(), userTeamEntity);
            }
            oldDataIdMap.put(userTeamEntity.getDataId(),userTypePojo);
        }
        switch (businessTypeEnum){
            case PAYMENT_SHEET:
                savePaymentSheetUser(corpid,oldDataIdMap,sourceDataIdMap,false);
                break;
            case PAY_SHEET:
                savePaySheetUser(corpid,oldDataIdMap,sourceDataIdMap,false);
                break;
            default:
                break;
        }
    }

    private void savePaymentSheetUser(String corpid, Map<Long, UserTypePojo> oldDataIdMap,Map<Long, UserTypePojo> sourceDataIdMap,boolean needThrow) throws XbbException {
        List<PaymentSheetUserEntity> insertUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> updateMainUserIdList = new ArrayList<>();
        List<UserTeamEntity> updateMainUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> updateCoorUserIdList = new ArrayList<>();
        List<UserTeamEntity> updateCoorUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PaymentSheetUserEntity> deleteUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        if ( oldDataIdMap.isEmpty() ) {
            sourceDataIdMap.forEach((key, value) -> {
                UserTypePojo sourceUser = value;
                if ( Objects.nonNull(sourceUser) ) {
                    sourceUser.getMainUserList().forEach(entity -> {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(entity, paymentSheetUserEntity);
                        paymentSheetUserEntity.setId(null);
                        paymentSheetUserEntity.setDataId(key);
                        insertUserTeamList.add(paymentSheetUserEntity);
                    });
                    sourceUser.getCoorUserList().forEach(entity -> {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(entity, paymentSheetUserEntity);
                        paymentSheetUserEntity.setId(null);
                        paymentSheetUserEntity.setDataId(key);
                        insertUserTeamList.add(paymentSheetUserEntity);
                    });
                }
            });
        }

//        oldDataIdMap.forEach((key, value) -> {
        for ( Map.Entry<Long, UserTypePojo> entry : oldDataIdMap.entrySet()) {
            Map<String, UserTeamEntity> oldMainUserTeam = entry.getValue().getOldMainUserMap();
            Map<String, UserTeamEntity> oldCoorUserteam = entry.getValue().getOldCoorUserMap();
            Map<String, UserTeamEntity> copyMainUserTeam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String, UserTeamEntity> copyCoorUserteam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            copyMainUserTeam.putAll(oldMainUserTeam);
            copyCoorUserteam.putAll(oldCoorUserteam);
            try {
                Long key = entry.getKey();
                UserTypePojo value = entry.getValue();
                UserTypePojo oldUser = value;
                UserTypePojo sourceUser = sourceDataIdMap.get(key);
                if ( Objects.nonNull(sourceUser) ) {
                    for ( UserTeamEntity userTeamEntity : sourceUser.getMainUserList() ) {
                        String userId = userTeamEntity.getUserId();
                        UserTeamEntity mainUserTeam = oldMainUserTeam.get(userId);
                        UserTeamEntity coorUserteam = oldCoorUserteam.get(userId);
                        userTeamEntity.setIsMain(BasicConstant.MAIN_USER);
                        if ( Objects.isNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                            PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                            BeanUtil.copyProperties(userTeamEntity, paymentSheetUserEntity);
                            paymentSheetUserEntity.setId(null);
                            paymentSheetUserEntity.setDataId(key);
                            insertUserTeamList.add(paymentSheetUserEntity);
                        } else if ( Objects.isNull(mainUserTeam) && Objects.nonNull(coorUserteam) ) {
                            PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                            BeanUtil.copyProperties(userTeamEntity, paymentSheetUserEntity);
                            updateMainUserTeamList.add(paymentSheetUserEntity);
                            updateMainUserIdList.add(paymentSheetUserEntity.getId());
                            copyCoorUserteam.remove(userId);
                        } else if ( Objects.nonNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                            copyMainUserTeam.remove(userId);
                        }
                    }

                    for ( UserTeamEntity userTeamEntity : sourceUser.getCoorUserList() ) {
                        String userId = userTeamEntity.getUserId();
                        UserTeamEntity mainUserTeam = oldMainUserTeam.get(userId);
                        UserTeamEntity coorUserteam = oldCoorUserteam.get(userId);
                        userTeamEntity.setIsMain(BasicConstant.COOP_USER);
                        if ( Objects.isNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                            PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                            BeanUtil.copyProperties(userTeamEntity, paymentSheetUserEntity);
                            paymentSheetUserEntity.setId(null);
                            paymentSheetUserEntity.setDataId(key);
                            insertUserTeamList.add(paymentSheetUserEntity);
                        } else if ( Objects.nonNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                            PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                            BeanUtil.copyProperties(userTeamEntity, paymentSheetUserEntity);
                            updateCoorUserTeamList.add(paymentSheetUserEntity);
                            updateMainUserIdList.add(paymentSheetUserEntity.getId());
                            copyMainUserTeam.remove(userId);
                        } else if ( Objects.nonNull(coorUserteam) && Objects.isNull(mainUserTeam) ) {
                            copyCoorUserteam.remove(userId);
                        }
                    }
                    copyMainUserTeam.forEach((deleteKey, deleteValue) -> {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(deleteValue, paymentSheetUserEntity);
                        deleteUserTeamList.add(paymentSheetUserEntity);
                    });
                    copyCoorUserteam.forEach((deleteKey, deleteValue) -> {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(deleteValue, paymentSheetUserEntity);
                        deleteUserTeamList.add(paymentSheetUserEntity);
                    });
                } else {
                    for ( UserTeamEntity userTeamEntity : oldUser.getMainUserList() ) {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(userTeamEntity, paymentSheetUserEntity);
                        deleteUserTeamList.add(paymentSheetUserEntity);
                    }
                    for ( UserTeamEntity userTeamEntity : oldUser.getMainUserList() ) {
                        PaymentSheetUserEntity paymentSheetUserEntity = new PaymentSheetUserEntity();
                        BeanUtil.copyProperties(userTeamEntity, paymentSheetUserEntity);
                        deleteUserTeamList.add(paymentSheetUserEntity);
                    }
                }
            } catch (Exception e) {
                LOG.error("回款单团队更新失败，失败理由是：", e);
            }
//        });
    }
        if ( CollectionsUtil.isNotEmpty(insertUserTeamList) ) {
            paymentSheetUserModel.insertBatch(insertUserTeamList, needThrow);
        }
        if ( CollectionsUtil.isNotEmpty(updateMainUserTeamList) ) {
            paymentSheetUserModel.batchUpdateByUserIdIn(corpid, updateMainUserIdList,updateMainUserTeamList,BasicConstant.MAIN_USER,null,needThrow);
        }
        if ( CollectionsUtil.isNotEmpty(updateCoorUserTeamList) ) {
            paymentSheetUserModel.batchUpdateByUserIdIn(corpid, updateCoorUserIdList,updateMainUserTeamList,BasicConstant.COOP_USER,null,needThrow);
        }
        if ( CollectionsUtil.isNotEmpty(deleteUserTeamList) ) {
            paymentSheetUserModel.batchDelete(corpid, deleteUserTeamList,needThrow);
        }
    }

    private void savePaySheetUser(String corpid, Map<Long, UserTypePojo> oldDataIdMap,Map<Long, UserTypePojo> sourceDataIdMap,boolean needThrow) throws XbbException {
        List<PayPlanSheetUserEntity> insertUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> updateMainUserIdList = new ArrayList<>();
        List<UserTeamEntity> updateMainUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> updateCoorUserIdList = new ArrayList<>();
        List<UserTeamEntity> updateCoorUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PayPlanSheetUserEntity> deleteUserTeamList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        //如果没有老数据，就等于新增团队
        if ( oldDataIdMap.isEmpty() ) {
            sourceDataIdMap.forEach((key, value) -> {
                UserTypePojo sourceUser = value;
                if ( Objects.nonNull(sourceUser)){
                    sourceUser.getMainUserList().forEach(entity->{
                        PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                        BeanUtil.copyProperties(entity, payPlanSheetUserEntity);
                        payPlanSheetUserEntity.setId(null);
                        payPlanSheetUserEntity.setDataId(key);
                        insertUserTeamList.add(payPlanSheetUserEntity);
                    });
                    sourceUser.getCoorUserList().forEach(entity->{
                        PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                        BeanUtil.copyProperties(entity, payPlanSheetUserEntity);
                        payPlanSheetUserEntity.setId(null);
                        insertUserTeamList.add(payPlanSheetUserEntity);
                    });
                }
            });
        }

        //如果有数据，就判断当前的新数据，是否和老数据出现重复，进行去重后作为唯一处理(如果在不同的合同内同时是A合同的负责人，B合同的协同人，这时就要当成负责人去处理)
//        oldDataIdMap.forEach((key, value)->{
            for ( Map.Entry<Long, UserTypePojo> entry : oldDataIdMap.entrySet()) {
                Map<String, UserTeamEntity> oldMainUserTeam = entry.getValue().getOldMainUserMap();
                Map<String, UserTeamEntity> oldCoorUserteam = entry.getValue().getOldCoorUserMap();
                Map<String, UserTeamEntity> copyMainUserTeam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, UserTeamEntity> copyCoorUserteam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                copyMainUserTeam.putAll(oldMainUserTeam);
                copyCoorUserteam.putAll(oldCoorUserteam);
                try {
                    Long key = entry.getKey();
                    UserTypePojo value = entry.getValue();
                    UserTypePojo oldUser = value;
                    UserTypePojo sourceUser = sourceDataIdMap.get(key);
                    if ( Objects.nonNull(sourceUser) ) {
                        for ( UserTeamEntity userTeamEntity : sourceUser.getMainUserList() ) {
                            String userId = userTeamEntity.getUserId();
                            UserTeamEntity mainUserTeam = oldMainUserTeam.get(userId);
                            UserTeamEntity coorUserteam = oldCoorUserteam.get(userId);
                            userTeamEntity.setIsMain(BasicConstant.MAIN_USER);
                            if ( Objects.isNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                                PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                                BeanUtil.copyProperties(userTeamEntity, payPlanSheetUserEntity);
                                payPlanSheetUserEntity.setId(null);
                                payPlanSheetUserEntity.setDataId(key);
                                insertUserTeamList.add(payPlanSheetUserEntity);
                            } else if ( Objects.isNull(mainUserTeam) && Objects.nonNull(coorUserteam) ) {
                                PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                                BeanUtil.copyProperties(userTeamEntity, payPlanSheetUserEntity);
                                updateMainUserTeamList.add(payPlanSheetUserEntity);
                                updateMainUserIdList.add(payPlanSheetUserEntity.getId());
                                copyCoorUserteam.remove(userId);
                            } else if ( Objects.nonNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                                copyMainUserTeam.remove(userId);
                            }
                        }

                        for ( UserTeamEntity userTeamEntity : sourceUser.getCoorUserList() ) {
                            String userId = userTeamEntity.getUserId();
                            UserTeamEntity mainUserTeam = oldMainUserTeam.get(userId);
                            UserTeamEntity coorUserteam = oldCoorUserteam.get(userId);
                            userTeamEntity.setIsMain(BasicConstant.COOP_USER);
                            if ( Objects.isNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                                PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                                BeanUtil.copyProperties(userTeamEntity, payPlanSheetUserEntity);
                                payPlanSheetUserEntity.setId(null);
                                payPlanSheetUserEntity.setDataId(key);
                                insertUserTeamList.add(payPlanSheetUserEntity);
                            } else if ( Objects.nonNull(mainUserTeam) && Objects.isNull(coorUserteam) ) {
                                PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                                BeanUtil.copyProperties(userTeamEntity, payPlanSheetUserEntity);
                                updateCoorUserTeamList.add(payPlanSheetUserEntity);
                                updateCoorUserIdList.add(payPlanSheetUserEntity.getId());
                                copyMainUserTeam.remove(userId);
                            } else if ( Objects.nonNull(coorUserteam) && Objects.isNull(mainUserTeam) ) {
                                copyCoorUserteam.remove(userId);
                            }
                        }
                        copyMainUserTeam.forEach((deleteKey, deleteValue) -> {
                            PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                            BeanUtil.copyProperties(deleteValue, payPlanSheetUserEntity);
                            deleteUserTeamList.add(payPlanSheetUserEntity);
                        });
                        copyCoorUserteam.forEach((deleteKey, deleteValue) -> {
                            PayPlanSheetUserEntity payPlanSheetUserEntity = new PayPlanSheetUserEntity();
                            BeanUtil.copyProperties(deleteValue, payPlanSheetUserEntity);
                            deleteUserTeamList.add(payPlanSheetUserEntity);
                        });
                    } else {
                        for ( UserTeamEntity userTeamEntity : oldUser.getMainUserList() ) {
                            PayPlanSheetUserEntity payPlantSheetUserEntity = new PayPlanSheetUserEntity();
                            BeanUtil.copyProperties(userTeamEntity, payPlantSheetUserEntity);
                            deleteUserTeamList.add(payPlantSheetUserEntity);
                        }
                        for ( UserTeamEntity userTeamEntity : oldUser.getMainUserList() ) {
                            PayPlanSheetUserEntity payPlantSheetUserEntity = new PayPlanSheetUserEntity();
                            BeanUtil.copyProperties(userTeamEntity, payPlantSheetUserEntity);
                            deleteUserTeamList.add(payPlantSheetUserEntity);
                        }
                    }
                } catch (Exception e) {
                    LOG.error("付款单团队更新失败，失败理由是：", e);
                }
//        });
            }
        if ( CollectionsUtil.isNotEmpty(insertUserTeamList) ) {
            payPlanSheetUserModel.insertBatch(insertUserTeamList,needThrow);
        }
        if ( CollectionsUtil.isNotEmpty(updateMainUserTeamList) ) {
            payPlanSheetUserModel.batchUpdateByUserIdIn(corpid, updateMainUserIdList,updateMainUserTeamList,BasicConstant.MAIN_USER,null,needThrow);
        }
        if ( CollectionsUtil.isNotEmpty(updateCoorUserTeamList) ) {
            payPlanSheetUserModel.batchUpdateByUserIdIn(corpid, updateCoorUserIdList,updateMainUserTeamList,BasicConstant.COOP_USER,null,needThrow);
        }
        if ( CollectionsUtil.isNotEmpty(deleteUserTeamList) ) {
            payPlanSheetUserModel.batchDelete(corpid, deleteUserTeamList, needThrow);
        }
    }


    /**
     * 获取团队对应的对象名称，涉及对象范围以UserTeamEnum为主
     * @param userTeamBatchSaveDTO
     * @return
     * @throws XbbException
     */
    private String getSaveName(UserTeamBatchSaveDTO userTeamBatchSaveDTO) throws XbbException{
        String saveName;
        String name;
        StringBuilder sb = new StringBuilder();
        String corpid = userTeamBatchSaveDTO.getCorpid();
        Integer businessType = userTeamBatchSaveDTO.getBusinessType();
        Long dataId = userTeamBatchSaveDTO.getDataId();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        PaasFormDataEntityExt paasFormDataEntityExt = saasGetHelp.getFormData(dataId, corpid, businessType);
        if (paasFormDataEntityExt == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        JSONObject data = paasFormDataEntityExt.getData();
        String serialNo = paasFormDataEntityExt.getSerialNo();
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                saveName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
                break;
            case SALES_OPPORTUNITY:
                name = data.getString(SalesOpportunityEnum.NAME.getAttr());
                saveName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                break;
            case CONTRACT:
                name = data.getString(ContractEnum.NAME.getAttr());
                saveName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                break;
            case CONTACT:
                saveName = FastJsonHelper.getStringOrDefaultFromFormData(data, ContactEnum.NAME.getAttr(), "");
                break;
            case SUPPLIER:
                saveName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                break;
            case PURCHASE:
                name = data.getString(PurchaseEnum.PURCHASE_NAME.getAttr());
                saveName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                break;
            case PRODUCTION_ORDER:
                saveName = serialNo;
                break;
            case BOM_BILL:
                name = data.getString(BomBillEnum.NAME.getAttr());
                saveName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                break;
            case PRODUCT:
                name = data.getString(ProductEnum.NAME.getAttr());
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(data, ProductEnum.PRODUCT_NO.getAttr(), "");
                saveName = name == null ? productNo : sb.append(name).append("（").append(productNo).append("）").toString();
                break;
            case WORK_ORDER:
                saveName = serialNo;
                break;
            case REFUND:
                name = data.getString(RefundEnum.REFUND_NAME.getAttr());
                saveName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                break;
            case SUPPLIER_CONTACT:
                saveName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.NAME.getAttr(), "");
                break;
            case PAYMENT:
                saveName = serialNo;
                break;
            case PAY_PLAN:
                saveName = serialNo;
                break;
            case WAREHOUSE:
                name = data.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr());
                saveName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                break;
            case QUOTATION:
                saveName = serialNo;
                break;
            case CLUE:
                saveName = FastJsonHelper.getStringOrDefaultFromFormData(data, ClueEnum.COMPANY_NAME.getAttr(), "");
                break;
            case MARKET_ACTIVITY:
                saveName = FastJsonHelper.getStringOrDefaultFromFormData(data, MarketActivityEnum.NAME.getAttr(), "");
                break;
            default:
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
        }
        return saveName;
    }

    @Override
    public UserTeamBatchSaveDTO beforeSaveMyTeam(BeforeSaveMyTeamDTO beforeSaveMyTeamDTO) throws XbbException {
        List<String> addMainUserList = beforeSaveMyTeamDTO.getAddMainUserList();
        List<String> addCoUserList = beforeSaveMyTeamDTO.getAddCoUserList();
        List<String> coUserToMainUserList = beforeSaveMyTeamDTO.getCoUserToMainUserList();
        List<String> mainUserToCoUserList = beforeSaveMyTeamDTO.getMainUserToCoUserList();
        List<String> delMainUserList = beforeSaveMyTeamDTO.getDelMainUserList();
        List<String> delCoUserList = beforeSaveMyTeamDTO.getDelCoUserList();
        Long dataId = beforeSaveMyTeamDTO.getDataId();
        String corpid = beforeSaveMyTeamDTO.getCorpid();
        Integer businessType = beforeSaveMyTeamDTO.getBusinessType();
        UserTeamBatchSaveDTO userTeamBatchSaveDTO = new UserTeamBatchSaveDTO();
        BeanUtil.copyProperties(beforeSaveMyTeamDTO, userTeamBatchSaveDTO);
        List<UserTeamBatchAddDTO> userTeamBatchAddDTOList = new ArrayList<>();
        List<UserTeamBatchUpdateDTO> userTeamBatchUpdateDTOList = new ArrayList<>();
        List<UserTeamBatchDeleteDTO> userTeamBatchDeleteDTOList = new ArrayList<>();
        if (Objects.equals(beforeSaveMyTeamDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            Map<Integer, List<String>> errorMsgMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<String> allErrorUserIds = judgeAddMainUser(dataId, corpid, businessType, errorMsgMap, addMainUserList, beforeSaveMyTeamDTO.getIsNew());
            Map<String, String> userNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(allErrorUserIds)) {
                List<UserEntity> userList = userModel.getByUserIdIn(corpid, allErrorUserIds, true);
                userList.forEach(user-> userNameMap.put(user.getUserId(), user.getName()));
            }
            List<ErrorMessagePojo> errorMessageList = new ArrayList<>();
            if (Objects.nonNull(errorMsgMap) && !errorMsgMap.isEmpty()) {
                for (Map.Entry<Integer, List<String>> entry : errorMsgMap.entrySet()) {
                    CustomerRuleEnum customerRuleEnum = CustomerRuleEnum.getByCode(entry.getKey());
                    List<String> businessNameList = new ArrayList<>();
                    entry.getValue().forEach(userId-> {
                        businessNameList.add(userNameMap.getOrDefault(userId, ""));
                    });
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.join(StringConstant.COMMA, businessNameList) +I18nMessageUtil.getMessage(I18nStringConstant.DISSATISFY) + customerRuleEnum.getName());
                }
            }
        } else if (Objects.equals(beforeSaveMyTeamDTO.getBusinessType(), XbbRefTypeEnum.CLUE.getCode())) {
            Map<Integer, List<String>> errorMsgMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<String> allErrorUserIds = judgeAddMainUser(dataId, corpid, businessType, errorMsgMap, addMainUserList, beforeSaveMyTeamDTO.getIsNew());
            Map<String, String> userNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(allErrorUserIds)) {
                List<UserEntity> userList = userModel.getByUserIdIn(corpid, allErrorUserIds, true);
                userList.forEach(user-> userNameMap.put(user.getUserId(), user.getName()));
            }
            List<ErrorMessagePojo> errorMessageList = new ArrayList<>();
            if (Objects.nonNull(errorMsgMap) && !errorMsgMap.isEmpty()) {
                for (Map.Entry<Integer, List<String>> entry : errorMsgMap.entrySet()) {
                    ClueRuleEnum clueRuleEnum = ClueRuleEnum.getByCode(entry.getKey());
                    List<String> businessNameList = new ArrayList<>();
                    entry.getValue().forEach(userId-> {
                        businessNameList.add(userNameMap.getOrDefault(userId, ""));
                    });
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.join(StringConstant.COMMA, businessNameList) +I18nMessageUtil.getMessage(I18nStringConstant.DISSATISFY) + clueRuleEnum.getName());
                }
            }
        }
        if (CollectionsUtil.isNotEmpty(addMainUserList)) {
            UserTeamBatchAddDTO userTeamBatchAddDTO = new UserTeamBatchAddDTO();
            BeanUtil.copyProperties(beforeSaveMyTeamDTO, userTeamBatchAddDTO);
            userTeamBatchAddDTO.setDataId(dataId);
            userTeamBatchAddDTO.setUserIdIn(addMainUserList);
            userTeamBatchAddDTO.setIsMain(BasicConstant.MAIN_USER);
            userTeamBatchAddDTOList.add(userTeamBatchAddDTO);
        }

        if(CollectionsUtil.isNotEmpty(addCoUserList)){
            UserTeamBatchAddDTO userTeamBatchAddDTO = new UserTeamBatchAddDTO();
            BeanUtil.copyProperties(beforeSaveMyTeamDTO, userTeamBatchAddDTO);
            userTeamBatchAddDTO.setDataId(dataId);
            userTeamBatchAddDTO.setUserIdIn(addCoUserList);
            userTeamBatchAddDTO.setIsMain(BasicConstant.COOP_USER);
            userTeamBatchAddDTOList.add(userTeamBatchAddDTO);
        }
        if (CollectionsUtil.isNotEmpty(delMainUserList)) {
            UserTeamBatchDeleteDTO userTeamBatchDeleteDTO = new UserTeamBatchDeleteDTO();
            BeanUtil.copyProperties(beforeSaveMyTeamDTO, userTeamBatchDeleteDTO);
            userTeamBatchDeleteDTO.setDel(DelEnum.DELETE.getDel());
            userTeamBatchDeleteDTO.setOtherId(dataId);
            userTeamBatchDeleteDTO.setUpdateUserIdIn(delMainUserList);
            userTeamBatchDeleteDTO.setIsMain(BasicConstant.MAIN_USER);
            userTeamBatchDeleteDTOList.add(userTeamBatchDeleteDTO);
        }
        if (CollectionsUtil.isNotEmpty(delCoUserList)) {
            UserTeamBatchDeleteDTO userTeamBatchDeleteDTO = new UserTeamBatchDeleteDTO();
            BeanUtil.copyProperties(beforeSaveMyTeamDTO, userTeamBatchDeleteDTO);
            userTeamBatchDeleteDTO.setDel(DelEnum.DELETE.getDel());
            userTeamBatchDeleteDTO.setOtherId(dataId);
            userTeamBatchDeleteDTO.setUpdateUserIdIn(delCoUserList);
            userTeamBatchDeleteDTO.setIsMain(BasicConstant.COOP_USER);
            userTeamBatchDeleteDTOList.add(userTeamBatchDeleteDTO);
        }
        if (CollectionsUtil.isNotEmpty(mainUserToCoUserList)) {
            UserTeamBatchUpdateDTO userTeamBatchUpdateDTO = new UserTeamBatchUpdateDTO();
            BeanUtil.copyProperties(beforeSaveMyTeamDTO, userTeamBatchUpdateDTO);
            userTeamBatchUpdateDTO.setBusinessType(businessType);
            userTeamBatchUpdateDTO.setIsMain(BasicConstant.COOP_USER);
            userTeamBatchUpdateDTO.setOtherId(dataId);
            userTeamBatchUpdateDTO.setUpdateUserIdIn(mainUserToCoUserList);
            userTeamBatchUpdateDTOList.add(userTeamBatchUpdateDTO);
        }
        if (CollectionsUtil.isNotEmpty(coUserToMainUserList)) {
            UserTeamBatchUpdateDTO userTeamBatchUpdateDTO = new UserTeamBatchUpdateDTO();
            BeanUtil.copyProperties(beforeSaveMyTeamDTO, userTeamBatchUpdateDTO);
            userTeamBatchUpdateDTO.setIsMain(BasicConstant.MAIN_USER);
            userTeamBatchUpdateDTO.setOtherId(dataId);
            userTeamBatchUpdateDTO.setUpdateUserIdIn(coUserToMainUserList);
            userTeamBatchUpdateDTOList.add(userTeamBatchUpdateDTO);
        }
        userTeamBatchSaveDTO.setUserTeamBatchAddDTOList(userTeamBatchAddDTOList);
        userTeamBatchSaveDTO.setUserTeamBatchUpdateDTOList(userTeamBatchUpdateDTOList);
        userTeamBatchSaveDTO.setUserTeamBatchDeleteDTOList(userTeamBatchDeleteDTOList);
        return userTeamBatchSaveDTO;
    }

    @Override
    public BeforeSaveMyTeamDTO verifyMyTeam(UserTeamDTO userTeamDTO) throws XbbException {
        Long dataId = userTeamDTO.getDataId();
        Long formId = userTeamDTO.getFormId();
        String corpid = userTeamDTO.getCorpid();
        Integer businessType = userTeamDTO.getBusinessType();
        Integer subBusinessType = userTeamDTO.getSubBusinessType();
        // 新的负责人
        List<String> newMainUserList = new ArrayList<>();
        if (userTeamDTO.getOwnerId() != null) {
            for (int i = 0; i < userTeamDTO.getOwnerId().size(); i++) {
                newMainUserList.add(Objects.toString(userTeamDTO.getOwnerId().get(i).getId(), ""));
            }
        }

        List<String> copyNewMainUserList = (List<String>)CloneUtil.deepClone(newMainUserList);
        // 新的协同人
        List<String> newCoUserList = new ArrayList<>();
        if (userTeamDTO.getCoUserId() != null) {
            userTeamDTO.getCoUserId().forEach(coUser-> newCoUserList.add(Objects.toString(coUser.getId(), "")));
        }
        copyNewMainUserList.retainAll(newCoUserList);
        if (CollectionsUtil.isNotEmpty(copyNewMainUserList)) {
            List<UserEntity> userList = userModel.getByUserIdIn(corpid, copyNewMainUserList, true);
            StringBuilder errorUserName = new StringBuilder();
            String errorUser = "";
            for (UserEntity userEntity : userList) {
                errorUserName.append(userEntity.getName()).append(StringConstant.COMMA);
            }
            if (!errorUserName.toString().isEmpty()) {
                errorUser = errorUserName.substring(0, errorUserName.length() - 1);
            }
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200024, String.format(BuinessDefaultErrorCodeEnum.API_ERROR_200024.getMsg(), errorUser));
        }
        // 判断权限的DTO
        String userId = userTeamDTO.getUserId();
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(userTeamDTO, handlerExplainDTO);
        if (StringUtil.isNotEmpty(userTeamDTO.getProcessCreatorId())) {
            userId = userTeamDTO.getProcessCreatorId();
            UserVO userVO = userService.getUserVO(corpid, userId, true, true);
            handlerExplainDTO.setLoginUser(userVO);
        }
        handlerExplainDTO.setUserId(userId);
        //客户这块对创建人特殊处理
        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
            if (Objects.nonNull(userTeamDTO.getData())) {
                userTeamDTO.setCreatorId(userTeamDTO.getData().getString(CustomerManagementEnum.CREATOR.getAttr()));
            }
        }
        handlerExplainDTO.setCreatorId(userTeamDTO.getCreatorId() == null ? userTeamDTO.getUserId() : userTeamDTO.getCreatorId());
        // 是否有添加权限
        Boolean haveMainAddPermission = true;
        Boolean haveCoUserAddPermission = true;
        // 获取协同人和负责人的解释
        FieldAttrEntity ownerField = new FieldAttrEntity();
        FieldAttrEntity coUserField = new FieldAttrEntity();
        if (!Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(explainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
            //仓库的负责人是array_2,没有协同人
            if(Objects.equals(businessType, XbbRefTypeEnum.WAREHOUSE.getCode())){
                ownerField = explainMap.get(WarehouseEnum.MANAGER_ID.getAttr());
            }else {
                ownerField = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
                coUserField = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderExplainEntityExt explainEntity = workOrderExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(explainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
            ownerField = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
            coUserField = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
        }
        BeforeSaveMyTeamDTO beforeSaveMyTeamDTO = new BeforeSaveMyTeamDTO();
        BeanUtil.copyProperties(userTeamDTO, beforeSaveMyTeamDTO);
        //离职人员
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("del", BasicConstant.ONE);
        //增加这个字段防止查询量太大
        param.put("userIdIn", newCoUserList);
        List<String> delUserIdList = userModel.getUserIds(param);

        // 编辑
        if (!userTeamDTO.getIsNew()) {
            // 老的负责人协同人
            List<String> oldMainUserList = new ArrayList<>();
            List<String> oldCoUserList = new ArrayList<>();
            // 获取协同人和负责人
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (UserTeamEnum.hasTeam(businessType)){
                Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),subBusinessType) || Objects.equals(XbbRefTypeEnum.CLUE_PUBLIC.getCode(),subBusinessType);
                getAnotherUserIdMap(Collections.singletonList(dataId), userTeamDTO.getCorpid(), businessType, isPublic, mainUserMap, coUserMap);
                oldMainUserList = mainUserMap.get(dataId);
                oldCoUserList = coUserMap.get(dataId);
            }  else {
                CoUserListDTO coUserListDTO = new CoUserListDTO();
                BeanUtil.copyProperties(userTeamDTO, coUserListDTO);
                coUserListDTO.setFormDataIdIn(Collections.singletonList(dataId));
                coUserMap = coUserService.coUserMap(coUserListDTO);
                oldMainUserList = Collections.singletonList(userTeamDTO.getCreatorId());
                oldCoUserList = coUserMap.get(dataId);
            }
            oldMainUserList = oldMainUserList == null ? new ArrayList<>() : oldMainUserList;
            oldCoUserList = oldCoUserList == null ? new ArrayList<>() : oldCoUserList;

            if (!Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
                if (CollectionsUtil.isEmpty(newMainUserList) && CollectionsUtil.isNotEmpty(oldMainUserList)) {
                    if (Objects.nonNull(userTeamDTO.getFromDetail()) || (!Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && !Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()))) {
                        // 详情页操作团队，至少需要保留一个负责人；因为客户保存，可以将负责人去掉直接进入公海池，所以除了客户模块的保存至少要保留一个负责人
                        throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200016);
                    }
                }
            }
            // 新增负责人，新增协同人，删除负责人，删除协同人，由协同人升级为负责人，由负责人降级为协同人
            List<String> addMainUserList = new ArrayList<>();
            List<String> addCoUserList = new ArrayList<>();
            List<String> delMainUserList = new ArrayList<>();
            List<String> delCoUserList = new ArrayList<>();
            List<String> coUserToMainUserList = new ArrayList<>();
            List<String> mainUserToCoUserList = new ArrayList<>();
            // 负责人
            List<String> copyNewMainList = (List<String>)CloneUtil.deepClone(newMainUserList);
            List<String> copyOldMainList = (List<String>)CloneUtil.deepClone(oldMainUserList);
            copyNewMainList.removeAll(oldMainUserList);
            addMainUserList = copyNewMainList;
            // 旧的主负责人去掉与新的主负责人的交集 既为删除的主负责人
            //copyOldMainList.removeAll(newMainUserList);
            // 防止意外情况出现同样的负责人
            newMainUserList.forEach(item->{
                copyOldMainList.remove(item);
            });
            delMainUserList = copyOldMainList;

            //这里从编辑页进来的,需要有已离职校验,从详情页进来的不需要,根据isEdit判断
            //按道理销售机会的编辑页进去也应该校验离职, 但是居然没有, 震惊= =
            checkAddUserList(userTeamDTO.getIsEdit(), userTeamDTO.getIsNew(), corpid,
                    oldMainUserList, addMainUserList, copyOldMainList, delUserIdList);

            // 协同人
            List<String> copyNewCoUserList = (List<String>)CloneUtil.deepClone(newCoUserList);
            List<String> copyOldCoUserList = (List<String>)CloneUtil.deepClone(oldCoUserList);
            copyNewCoUserList.removeAll(oldCoUserList);
            addCoUserList = copyNewCoUserList;
            //copyOldCoUserList.removeAll(newCoUserList);
            // 防止意外情况出现同样的协同人
            newCoUserList.forEach(item->{
                copyOldCoUserList.remove(item);
            });
            delCoUserList = copyOldCoUserList;

            //这里从编辑页进来的,需要有已离职校验,从详情页进来的不需要,根据isEdit判断
            checkAddUserList(userTeamDTO.getIsEdit(), userTeamDTO.getIsNew(), corpid,
                    oldCoUserList, addCoUserList, copyOldCoUserList, delUserIdList);

            // 协同人升级为负责人
            List<String> copyDelCoUserList = (List<String>)CloneUtil.deepClone(delCoUserList);
            List<String> copyDelMainUserList = (List<String>)CloneUtil.deepClone(delMainUserList);
            //协同人升级为负责人时,
            if (ExplainUtil.judgeListContainsAnotherListOneValue(addMainUserList, delCoUserList)) {
                delCoUserList.removeAll(addMainUserList);
                addMainUserList.removeAll(copyDelCoUserList);
                copyDelCoUserList.removeAll(delCoUserList);
                coUserToMainUserList.addAll(copyDelCoUserList);
            }
            // 负责人降级为协同人
            if (ExplainUtil.judgeListContainsAnotherListOneValue(addCoUserList, delMainUserList)) {
                delMainUserList.removeAll(addCoUserList);
                addCoUserList.removeAll(copyDelMainUserList);
                copyDelMainUserList.removeAll(delMainUserList);
                mainUserToCoUserList.addAll(copyDelMainUserList);
            }
            UserEntity userEntity = userModel.getByKey(userId, corpid);
            if(null == userEntity){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004);
            }
            //Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, businessType, null);
            List<String> subIdList = userModel.getManageUser(userEntity);

            handlerExplainDTO.setCoUserId(oldCoUserList);
            handlerExplainDTO.setOwnerId(oldMainUserList);
            handlerExplainDTO.setSubIdList(subIdList);
            Boolean haveMainDelPermission = true;
            Boolean haveCoUserDelPermission = true;
            haveMainAddPermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
            haveMainDelPermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
            haveCoUserDelPermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());
            haveCoUserAddPermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
            if (!addMainUserList.isEmpty()) {
                if (!haveMainAddPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007);
                }
                beforeSaveMyTeamDTO.setAddMainUserList(addMainUserList);
            }
            if(!addCoUserList.isEmpty()){
                if (!haveCoUserAddPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390008);
                }
                beforeSaveMyTeamDTO.setAddCoUserList(addCoUserList);
            }
            if (!delMainUserList.isEmpty()) {
                if (!haveMainDelPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390005);
                }
                if (!Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
                    beforeSaveMyTeamDTO.setDelMainUserList(delMainUserList);
                }
            }
            if (!delCoUserList.isEmpty()) {
                if (!haveCoUserDelPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390006);
                }
                beforeSaveMyTeamDTO.setDelCoUserList(delCoUserList);
            }
            if (!mainUserToCoUserList.isEmpty()) {
                if (!haveMainDelPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390005);
                }
                if (!haveCoUserAddPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390008);
                }
                beforeSaveMyTeamDTO.setMainUserToCoUserList(mainUserToCoUserList);
            }
            if (!coUserToMainUserList.isEmpty()) {
                if (!haveCoUserDelPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390006);
                }
                if (!haveMainAddPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007);
                }
                beforeSaveMyTeamDTO.setCoUserToMainUserList(coUserToMainUserList);
            }

        } else {
            haveMainAddPermission = ExplainUtil.advancedOperationHavePermission(ownerField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
            haveCoUserAddPermission = ExplainUtil.advancedOperationHavePermission(coUserField, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
            if (!newMainUserList.isEmpty()) {
                if (!haveMainAddPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007);
                }
                checkAddUserList(userTeamDTO.getIsEdit(), userTeamDTO.getIsNew(), corpid,
                        newMainUserList,null, null, delUserIdList);
                //allErrorUserIds = judgeCustomerAddMainUser(dataId, corpid, businessType, errorMsgMap, newMainUserList, true)
                beforeSaveMyTeamDTO.setAddMainUserList(newMainUserList);
            }

            if (!newCoUserList.isEmpty()) {
                if (!haveCoUserAddPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390008);
                }

                checkAddUserList(userTeamDTO.getIsEdit(), userTeamDTO.getIsNew(), corpid,
                        newCoUserList,null, null, delUserIdList);

                beforeSaveMyTeamDTO.setAddCoUserList(newCoUserList);
            }
        }
        return beforeSaveMyTeamDTO;
    }


    /**
     * 通用校验负责人和协同人, 编辑页离职校验, 编辑页不需要
     * 点击复制页进来, 已经离职的负责人/协同人不应该被添加
     *
     * @param isEdit 是否是编辑页进来的
     * @param isNew 是否是复制的
     */
    private void checkAddUserList(Boolean isEdit,
                                  Boolean isNew,
                                  String corpid,
                                  List<String> oldUserList,
                                  List<String> addUserList,
                                  List<String> copyOldList,
                                  List<String> delUserIdList) throws XbbException {
        //因为会处理负责人/协同人两次,delUserIdList要拷贝防止脏数据
        List<String> tempList = new ArrayList<>(delUserIdList);
        //取交集
        tempList.retainAll(oldUserList);
        //复制页进来的
        if (isNew) {
            //如果复制的负责人/协同人里有离职人员,则报错
            Optional.ofNullable(tempList)
                    .filter(t -> CollectionsUtil.isEmpty(t))
                    .orElseThrow(() -> new XbbException(SystemErrorCodeEnum.API_ERROR_100127));
        }
        //编辑页进来的
        else if (isEdit) {
            //编辑页里面需要有已离职校验,这里要添加到addCoUserList中让其报错
            addUserList.addAll(tempList);
            //去掉真正要删除的
            addUserList.removeAll(copyOldList);
        }

    }

    public List<String> judgeAddMainUser(Long dataId, String corpid, Integer businessType, Map<Integer, List<String>> errorMsgMap, List<String> addMainUserList, boolean isNew) throws XbbException {
        List<String> allErrorUserList = new ArrayList<>();
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            List<String> errorUserIdList;
            if (CollectionsUtil.isNotEmpty(addMainUserList)) {
                List<UserEntity> userEntities = userModel.getByUserIdIn(corpid, addMainUserList,false);
                Map<String, UserEntity> userEntityMap = new HashMap<>(addMainUserList.size());
                userEntities.forEach(item->{
                    userEntityMap.put(item.getUserId(), item);
                });
                List<CustomerRuleEntity> ruleList = new ArrayList<>();
                //公海高级模式兼容老逻辑
                publicSeniorRuleHelp.getPublicSeniorRuleList(corpid,businessType,ruleList,new ArrayList<>());
                for (String addUserId : addMainUserList) {
                    UserEntity userEntity = userEntityMap.get(addUserId);
                    if (Objects.isNull(userEntity)) {
                        continue;
                    }
                    Integer type = customerRuleService.canGainCustomer(corpid, userEntity, dataId, ruleList, BasicConstant.ZERO);
                    Boolean flag = type == 0;
                    if (!flag) {
                        // 新建时不判断捞取频率规则
                        if (isNew && Objects.equals(type, CustomerRuleEnum.GAIN_RATE_RULE.getCode())) {
                            continue;
                        }
                        errorUserIdList = errorMsgMap.get(type) == null ? new ArrayList<>() : errorMsgMap.get(type);
                        errorUserIdList.add(addUserId);
                        allErrorUserList.add(addUserId);
                        errorMsgMap.put(type, errorUserIdList);
                    }
                }
                addMainUserList.removeIf(mainUser -> allErrorUserList.contains(mainUser));
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            List<String> errorUserIdList;
            if (CollectionsUtil.isNotEmpty(addMainUserList)) {
                List<UserEntity> userEntities = userModel.getByUserIdIn(corpid, addMainUserList,false);
                Map<String, UserEntity> userEntityMap = new HashMap<>(addMainUserList.size());
                userEntities.forEach(item->{
                    userEntityMap.put(item.getUserId(), item);
                });
                List<ClueRuleEntity> ruleList = new ArrayList<>();
                //公海高级模式兼容老逻辑
                publicSeniorRuleHelp.getPublicSeniorRuleList(corpid,businessType,new ArrayList<>(),ruleList);
                for (String addUserId : addMainUserList) {
                    UserEntity userEntity = userEntityMap.get(addUserId);
                    if (Objects.isNull(userEntity)) {
                        continue;
                    }
                    Integer type = clueRuleService.canGainClue(corpid, userEntity, dataId, ruleList, BasicConstant.ZERO);
                    Boolean flag = type == 0;
                    if (!flag) {
                        // 新建时不判断捞取频率规则
                        if (isNew && Objects.equals(type, ClueRuleEnum.GAIN_RATE_RULE.getCode())) {
                            continue;
                        }
                        errorUserIdList = errorMsgMap.get(type) == null ? new ArrayList<>() : errorMsgMap.get(type);
                        errorUserIdList.add(addUserId);
                        allErrorUserList.add(addUserId);
                        errorMsgMap.put(type, errorUserIdList);
                    }
                }
                addMainUserList.removeIf(mainUser -> allErrorUserList.contains(mainUser));
            }
        }
        return allErrorUserList;
    }


    private void specialBusinessHandle(ValidateDataDTO validateDataDTO,Map<String, FieldAttrEntity> explainMap) throws XbbException{
        FieldAttrEntity ownerFieldAttr = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
        if (Objects.isNull(ownerFieldAttr)) {
            return;
        }
        // 新的负责人
        List<String> newMainUserList = new ArrayList<>();
        // 老的负责人
        List<String> oldMainUserList = validateDataDTO.getOldOwnerId() == null ? new ArrayList<>() : Collections.singletonList(validateDataDTO.getOldOwnerId());
        validateDataDTO.getOwnerIds().forEach(owner->newMainUserList.add(Objects.toString(owner.getId(), "")));
        String creatorId = validateDataDTO.getCreatorId() == null ? validateDataDTO.getUserId() :validateDataDTO.getCreatorId();
        // 负责人
        List<String> copyNewMainList = (List<String>)CloneUtil.deepClone(newMainUserList);
        List<String> copyOldMainList = (List<String>)CloneUtil.deepClone(oldMainUserList);
        //获取当前登录人的信息
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(validateDataDTO.getLoginUser(),userEntity);

        //Integer dataPermission = userModel.getDataPermission(userEntity);
        List<String> subIdList = userModel.getManageUser(userEntity);
        //采购退货单、装配出入库单、入库单、出库单、盘点单、调拨单 只有负责人
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(validateDataDTO, handlerExplainDTO);
        handlerExplainDTO.setCreatorId(creatorId);
        handlerExplainDTO.setOwnerId(oldMainUserList);
        handlerExplainDTO.setSubIdList(subIdList);
        String userId = validateDataDTO.getUserId();
        if (StringUtil.isNotEmpty(validateDataDTO.getProcessCreatorId())) {
            userId = validateDataDTO.getProcessCreatorId();
            UserVO userVO = userService.getUserVO(validateDataDTO.getCorpid(), userId, true, true);
            handlerExplainDTO.setLoginUser(userVO);
        }
        handlerExplainDTO.setUserId(userId);
        Boolean haveMainAddPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.ADD.getOperation());
        Boolean haveMainDelPermission = ExplainUtil.advancedOperationHavePermission(ownerFieldAttr, handlerExplainDTO, FieldAdvanceOperationEnum.DEL.getOperation());

        if(CollectionsUtil.isEmpty(copyNewMainList) && CollectionsUtil.isEmpty(copyOldMainList)){
            if(BasicConstant.ONE.equals(ownerFieldAttr.getRequired())) {
                if(haveMainAddPermission){
                    List<ReturnUserAndDepartmentPojo> ownerIds = validateDataDTO.getOwnerIds();
                    if(CollectionsUtil.isEmpty(ownerIds)){
                        ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                        returnUserAndDepartmentPojo.setId(userEntity.getId());
                        returnUserAndDepartmentPojo.setId(userEntity.getName());
                        returnUserAndDepartmentPojo.setAvatar(userEntity.getAvatar());
                        ownerIds.add(returnUserAndDepartmentPojo);
                    }
                }else {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007,UserTeamErrorCodeEnum.API_ERROR_390007.getMsg());
                }
            }else {
                if(!haveMainAddPermission) {
                    throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007, UserTeamErrorCodeEnum.API_ERROR_390007.getMsg());
                }
            }
        }else if(CollectionsUtil.isNotEmpty(copyNewMainList) && CollectionsUtil.isEmpty(copyOldMainList)){
            if(!haveMainAddPermission){
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007,UserTeamErrorCodeEnum.API_ERROR_390007.getMsg());
            }
        }else if(CollectionsUtil.isEmpty(copyNewMainList) && CollectionsUtil.isNotEmpty(copyOldMainList)){
            if(!haveMainDelPermission){
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390005,UserTeamErrorCodeEnum.API_ERROR_390005.getMsg());
            }
        }else if(CollectionsUtil.isNotEmpty(copyNewMainList) && CollectionsUtil.isNotEmpty(copyOldMainList)){
            if(!haveMainDelPermission && !Objects.equals(copyNewMainList.get(0), copyOldMainList.get(0))) {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390005,UserTeamErrorCodeEnum.API_ERROR_390005.getMsg());
            }else if(!haveMainAddPermission && !Objects.equals(copyNewMainList.get(0), copyOldMainList.get(0))){
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_390007,UserTeamErrorCodeEnum.API_ERROR_390007.getMsg());
            }
        }
    }

    @Override
    public void getUserMap(List<Long> dataIdList, String corpid, Integer businessType, Boolean isPublic, Map<Long, String> mainUserMap, Map<Long, String> coUserMap) {
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<UserTeamEntity> userTeamEntityList = businessUserTeamHelp.getUserTeamList(dataIdList, corpid, businessType, isPublic);
        map.put(ParameterConstant.CORPID, corpid);
        map.put(ParameterConstant.DEL, DelEnum.DELETE.getDel());
        List<UserEntity> delUser = userModel.findEntitys(map);
        List<String> delUserIdList = new ArrayList<>();
        delUser.forEach(userEntity -> delUserIdList.add(userEntity.getUserId()));
        for (UserTeamEntity entity : userTeamEntityList) {
            String name = "";
            if (Objects.equals(entity.getIsMain(),1)){
                if (mainUserMap.containsKey(entity.getDataId())) {
                    name += mainUserMap.get(entity.getDataId()) + ",";
                }
                if (!delUserIdList.contains(entity.getUserId())) {
                    mainUserMap.put(entity.getDataId(), name + entity.getUserName());
                }
            }else {
                if (coUserMap.containsKey(entity.getDataId())) {
                    name += coUserMap.get(entity.getDataId()) + ",";
                }
                if (!delUserIdList.contains(entity.getUserId())) {
                    coUserMap.put(entity.getDataId(), name + entity.getUserName());
                }
            }
        }
    }

    @Override
    public void getVisableDepAndUser(Set<String> userIdList, String corpid,Long productId,List<String> visableDep,List<String> visableUser){
        businessUserTeamHelp.getVisableDepAndUser(userIdList, corpid, productId, visableDep, visableUser);
    }

    @Override
    public void handoverRemoveUser(String corpid, List<Long> removeIdList) throws XbbException {
        //客户团队根据id删除
        Map<Long,Set<String>> customerUserMap = customerUserModel.batchDeleteById(corpid,removeIdList, WriteRequest.RefreshPolicy.NONE);
        Runnable runnable = () -> {
            try {
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                for (Map.Entry<Long,Set<String>> entry : customerUserMap.entrySet()){
                    Set<String> userIds = entry.getValue();
                    for (String userId : userIds) {
                        BoolQueryBuilder innerQueryBuilder = boolQuery();
                        innerQueryBuilder.filter(termQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.CUSTOMER_ID), entry.getKey()));
                        innerQueryBuilder.filter(termQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.USER_ID), userId));
                        boolQueryBuilder.should(innerQueryBuilder);
                    }
                }
                boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
                List<PaasFormDataEntity> contactUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList("id", ContactTeamEnum.getAttrConnectData(ContactTeamEnum.DATA_ID)));
                if (!contactUserEntityList.isEmpty()){
                    List<ContactUserEntity> userTeamEntities = (List<ContactUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_CONTACT_TEAM, contactUserEntityList);
                    contactUserModel.deleteBatchUser(userTeamEntities, corpid);
                }
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                for (Map.Entry<Long,Set<String>> entry : customerUserMap.entrySet()){
                    Set<String> userIds = entry.getValue();
                    for (String userId : userIds) {
                        BoolQueryBuilder innerQueryBuilder = boolQuery();
                        innerQueryBuilder.filter(termQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.CUSTOMER_ID), entry.getKey()));
                        innerQueryBuilder.filter(termQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.USER_ID), userId));
                        boolQueryBuilder.should(innerQueryBuilder);
                    }
                }
                boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
                List<PaasFormDataEntity> contractUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT_TEAM, boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList("id", ContractTeamEnum.getAttrConnectData(ContractTeamEnum.DATA_ID)));
                if (!contractUserEntityList.isEmpty()){
                    List<ContractUserEntity> userTeamEntities = (List<ContractUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_CONTRACT_TEAM, contractUserEntityList);
                    contractUserModel.deleteBatchUser(userTeamEntities,corpid, DelEnum.DELETE.getDel());
                }
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                for (Map.Entry<Long,Set<String>> entry : customerUserMap.entrySet()){
                    Set<String> userIds = entry.getValue();
                    for (String userId : userIds) {
                        BoolQueryBuilder innerQueryBuilder = boolQuery();
                        innerQueryBuilder.filter(termQuery(QuotationTeamEnum.getEsAttr(QuotationTeamEnum.CUSTOMER_ID), entry.getKey()));
                        innerQueryBuilder.filter(termQuery(QuotationTeamEnum.getEsAttr(QuotationTeamEnum.USER_ID), userId));
                        boolQueryBuilder.should(innerQueryBuilder);
                    }
                }
                boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
                List<PaasFormDataEntity> quotationUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_QUOTATION_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList("id", QuotationTeamEnum.getEsAttr(QuotationTeamEnum.DATA_ID)));

                if (!quotationUserEntityList.isEmpty()){
                    List<QuotationUserEntity> userTeamEntities = (List<QuotationUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_QUOTATION_TEAM, quotationUserEntityList);
                    quotationUserModel.deleteBatchUser(userTeamEntities,corpid, DelEnum.DELETE.getDel());
                }
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                for (Map.Entry<Long,Set<String>> entry : customerUserMap.entrySet()){
                    Set<String> userIds = entry.getValue();
                    for (String userId : userIds) {
                        BoolQueryBuilder innerQueryBuilder = boolQuery();
                        innerQueryBuilder.filter(termQuery(OpportunityTeamEnum.getEsAttr(OpportunityTeamEnum.CUSTOMER_ID),entry.getKey()));
                        innerQueryBuilder.filter(termQuery(OpportunityTeamEnum.getEsAttr(OpportunityTeamEnum.USER_ID), userId));
                        boolQueryBuilder.should(innerQueryBuilder);
                    }
                }
                boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
                List<PaasFormDataEntity> opportunityUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList("id", OpportunityTeamEnum.getAttrConnectData(OpportunityTeamEnum.DATA_ID)));

                if (!opportunityUserEntityList.isEmpty()){
                    List<OpportunityUserEntity> userTeamEntities = (List<OpportunityUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM, opportunityUserEntityList);
                    opportunityUserModel.deleteBatchUser(userTeamEntities,corpid, DelEnum.DELETE.getDel());
                }
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                for (Map.Entry<Long,Set<String>> entry : customerUserMap.entrySet()){
                    Set<String> userIds = entry.getValue();
                    for (String userId : userIds) {
                        BoolQueryBuilder innerQueryBuilder = boolQuery();
                        innerQueryBuilder.filter(termQuery(PaymentTeamEnum.getEsAttr(PaymentTeamEnum.CUSTOMER_ID), entry.getKey()));
                        innerQueryBuilder.filter(termQuery(PaymentTeamEnum.getEsAttr(PaymentTeamEnum.USER_ID),userId));
                        boolQueryBuilder.should(innerQueryBuilder);
                    }
                }
                boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
                List<PaasFormDataEntity> paymentUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM,boolQueryBuilder, PaasFormDataEntity.class,Arrays.asList("id", PaymentTeamEnum.getAttrConnectData(PaymentTeamEnum.DATA_ID)));
                if (!paymentUserEntityList.isEmpty()){
                    List<PaymentUserEntity> userTeamEntities = (List<PaymentUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, paymentUserEntityList);
                    paymentUserModel.deleteBatchUser(userTeamEntities, corpid);
                }
                //预收款余额，考虑方法的提取
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                for (Map.Entry<Long,Set<String>> entry : customerUserMap.entrySet()){
                    Set<String> userIds = entry.getValue();
                    for (String userId : userIds) {
                        BoolQueryBuilder innerQueryBuilder = boolQuery();
                        innerQueryBuilder.filter(termQuery(PaymentBalanceTeamEnum.getEsAttr(PaymentBalanceTeamEnum.CUSTOMER_ID), entry.getKey()));
                        innerQueryBuilder.filter(termQuery(PaymentBalanceTeamEnum.getEsAttr(PaymentBalanceTeamEnum.USER_ID),userId));
                        boolQueryBuilder.should(innerQueryBuilder);
                    }
                }
                boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
                List<PaasFormDataEntity> paymentBalanceUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_PAYMENT_BALANCE_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Arrays.asList("id", PaymentBalanceTeamEnum.getAttrConnectData(PaymentBalanceTeamEnum.DATA_ID)));
                if (!paymentBalanceUserEntityList.isEmpty()){
                    List<PaymentBalanceUserEntity> userTeamEntities = (List<PaymentBalanceUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_PAYMENT_BALANCE_TEAM, paymentBalanceUserEntityList);
                    paymentBalanceUserModel.deleteBatchUser(userTeamEntities, corpid);
                }
            } catch (XbbException e) {
                LOG.error("listBatchService.handoverRemoveUser error：", e);
            }
        };
        threadPoolBeanConfig.listBatchThreadPool().execute(runnable);
    }



    @Override
    public void handoverInsertUser(String corpid, List<CustomerUserEntity> insertBatchList, String userId) throws XbbException {
        customerUserModel.insertBatch(insertBatchList, false);
        List<Long> customerIdList = new ArrayList<>();
        for (CustomerUserEntity entity : insertBatchList){
            customerIdList.add(entity.getDataId());
        }
        Runnable runnable = () -> {
            try {
                updateUserTeamByCustomer(customerIdList,corpid,insertBatchList.get(0));
            } catch (XbbException e) {
                e.printStackTrace();
                LOG.error("listBatchService.handoverInsertUser error：", e);
            }
        };
        threadPoolBeanConfig.listBatchThreadPool().execute(runnable);
    }

    @Override
    public void handoverInsertUser(List<UserTeamEntity> userTeamEntities, HandoverDTO handoverDTO, Map<Long, PaasFormDataEntityExt> mainBusinessEntity, Map<String, UserEntity> userEntityMap, List<Long> dataIds) throws XbbException {
        Integer businessType = handoverDTO.getBusinessType();
        String handoverUserId = handoverDTO.getHandoverUserId();
        UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO = new UserTeamBatchAddByOtherBusinessDTO();
        BeanUtil.copyProperties(handoverDTO, userTeamBatchAddByOtherBusinessDTO);
        userTeamBatchAddByOtherBusinessDTO.setIsMain(BasicConstant.MAIN_USER);
        userTeamBatchAddByOtherBusinessDTO.setUserIdIn(Arrays.asList(handoverUserId));
        try {
            XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            switch (refTypeEnum) {
                case CONTRACT:
                case ORDER:
                    List<ContractUserEntity> contractUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, contractUserEntities, ContractUserEntity.class, false);
                    for (ContractUserEntity userEntity : contractUserEntities) {
                        PaasFormDataEntityExt contractEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(contractEntity.getData(), ContractEnum.LINK_CUSTOMER.getAttr(), 0L));
                    }
                    contractUserModel.insertBatch(contractUserEntities, false);
                    Runnable runnable = () -> {
                        try {
                            userTeamBatchAddByOtherBusinessDTO.setSourceBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
                            // 退货退款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.REFUND.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(RefundEnum.CONTRACT_ID.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(RefundEnum.CUSTOMER_ID.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            // 用完销毁这个属性
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(null);
                            // 回款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PaymentEnum.CONTRACT.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(PaymentEnum.CUSTOMER.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                        } catch (XbbException e) {
                            LOG.error("listBatchService.handoverInsertUser error", e);
                        }
                    };
                    threadPoolBeanConfig.listBatchThreadPool().execute(runnable);
                    break;
                case SALES_OPPORTUNITY:
                    List<OpportunityUserEntity> opportunityUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, opportunityUserEntities, OpportunityUserEntity.class, false);
                    for (OpportunityUserEntity userEntity : opportunityUserEntities) {
                        PaasFormDataEntityExt oppEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(oppEntity.getData(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), 0L));
                    }
                    opportunityUserModel.insertBatch(opportunityUserEntities, false);
                    break;
                case REFUND:
                case RETURN:
                    List<RefundUserEntity> refundUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, refundUserEntities, RefundUserEntity.class, false);
                    for (RefundUserEntity userEntity : refundUserEntities) {
                        PaasFormDataEntityExt refundEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(refundEntity.getData(), RefundEnum.CUSTOMER_ID.getAttr(), 0L));
                        userEntity.setContractId(FastJsonHelper.getLongOrDefaultFromFormData(refundEntity.getData(), RefundEnum.CONTRACT_ID.getAttr(), 0L));
                    }
                    refundUserModel.insertBatch(refundUserEntities, false);
                    break;
                case QUOTATION:
                    List<QuotationUserEntity> quotationUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, quotationUserEntities, QuotationUserEntity.class, false);
                    for (QuotationUserEntity userEntity : quotationUserEntities) {
                        PaasFormDataEntityExt quotationEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(quotationEntity.getData(), QuotationEnum.CUSTOMER_ID.getAttr(), 0L));
                    }
                    quotationUserModel.insertBatch(quotationUserEntities, false);
                    break;
                case SUPPLIER:
                    List<SupplierUserEntity> supplierUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, supplierUserEntities, SupplierUserEntity.class, false);
                    supplierUserModel.insertBatch(supplierUserEntities, false);
                    Runnable runnable1 = () -> {
                        try {
                            // 供应商联系人
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(SupplierContactEnum.SUPPLIER_ID.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                        } catch (XbbException e) {
                            LOG.error("listBatchService.handoverInsertUser error", e);
                        }
                    };
                    threadPoolBeanConfig.listBatchThreadPool().execute(runnable1);
                    break;
                case PURCHASE:
                    List<PurchaseUserEntity> purchaseUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, purchaseUserEntities, PurchaseUserEntity.class, false);
                    purchaseUserModel.insertBatch(purchaseUserEntities, false);
                    Runnable runnable2 = () -> {
                        try {
                            // 付款计划
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PayPlanEnum.LINK_PURCHASE.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(PayPlanEnum.LINK_SUPPLIER.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setSourceBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                        } catch (XbbException e) {
                            LOG.error("listBatchService.handoverInsertUser error", e);
                        }
                    };
                    threadPoolBeanConfig.listBatchThreadPool().execute(runnable2);
                    break;
                case BOM_BILL:
                    List<BomUserEntity> bomUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, bomUserEntities, BomUserEntity.class, false);
                    bomUserModel.insertBatch(bomUserEntities, false);
                    break;
                case PRODUCTION_ORDER:
                    List<ProductionOrderUserEntity> orderUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, orderUserEntities, ProductionOrderUserEntity.class, false);
                    productionOrderUserModel.insertBatch(orderUserEntities, false);
                    break;
                case CLUE:
                    List<ClueUserEntity> clueUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, clueUserEntities, ClueUserEntity.class, false);
                    clueUserModel.insertBatch(clueUserEntities);
                    break;
                case MARKET_ACTIVITY:
                    List<MarketActivityUserEntity> marketActivityUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, marketActivityUserEntities, MarketActivityUserEntity.class, false);
                    marketActivityUserModel.insertBatch(marketActivityUserEntities,false);
                    break;
                case WAREHOUSE:
                    List<WarehouseUserEntity> warehouseUserEntityList = warehouseTeamTransferSubForm.transferUserTeamUserToWarehouseUser(userTeamEntities);
                    warehouseUserModel.insertBatch(warehouseUserEntityList,false);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            LOG.error("UserTeamServiceimpl.handoverInsertUser error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

    }


    @Override
    public void updateUserTeamByCustomer(List<Long> customerIdList, String corpid, UserTeamEntity userTeamEntity) throws XbbException {
        if (CollectionsUtil.isEmpty(customerIdList)) {
            return;
        }
        Map<Long,Long> customerMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> idList = updateUserTeamGetId(customerIdList,corpid,XbbRefTypeEnum.CONTACT.getCode(),customerMap,new HashMap<>());
        updateContactTeam(idList,corpid,userTeamEntity,customerMap);
        customerMap.clear();
        idList = updateUserTeamGetId(customerIdList,corpid,XbbRefTypeEnum.CONTRACT.getCode(),customerMap,new HashMap<>());
        updateContractTeam(idList,corpid,userTeamEntity,customerMap);
        customerMap.clear();
        idList = updateUserTeamGetId(customerIdList,corpid,XbbRefTypeEnum.QUOTATION.getCode(),customerMap,new HashMap<>());
        updateQuotationTeam(idList,corpid,userTeamEntity,customerMap);
        customerMap.clear();
        idList = updateUserTeamGetId(customerIdList,corpid,XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(),customerMap,new HashMap<>());
        updateOpportunityTeam(idList,corpid,userTeamEntity,customerMap);
        customerMap.clear();
        Map<Long,Long> contractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        idList = updateUserTeamGetId(customerIdList,corpid,XbbRefTypeEnum.PAYMENT.getCode(),customerMap,contractMap);
        updatePaymentTeam(idList,corpid,userTeamEntity,customerMap,contractMap);
        //预收款余额团队
        customerMap.clear();
        idList = updateUserTeamGetId(customerIdList,corpid,XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),customerMap,new HashMap<>());
        updatePaymentBalanceTeam(idList,corpid,userTeamEntity,customerMap);
        // 处理回款单或付款单的团队
        for (Long id : customerIdList) {
            updateSheetTeam(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT, id);
        }
    }


    private List<Long> updateUserTeamGetId(List<Long> customerIdList, String corpid, Integer businessType, Map<Long,Long> customerMap,Map<Long,Long> contractMap) throws XbbException {
        if(CollectionsUtil.isEmpty(customerIdList)){
            return  new ArrayList<>();
        }
        String customerAttr;
        String contractAttr = "";
        IndexTypeEnum indexTypeEnum;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        boolean balance= false;
        switch (xbbRefTypeEnum){
            case CONTRACT:
                customerAttr = ContractEnum.LINK_CUSTOMER.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CONTRACT;
                break;
            case CONTACT:
                customerAttr = ContactEnum.CUSTOMER_NAME.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_CONTACT;
                break;
            case SALES_OPPORTUNITY:
                customerAttr = SalesOpportunityEnum.CUSTOMER_NAME.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_OPPORTUNITY;
                break;
            case PAYMENT:
                customerAttr = PaymentEnum.CUSTOMER.getAttr();
                contractAttr = PaymentEnum.CONTRACT.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAYMENT;
                break;
            case QUOTATION:
                customerAttr = QuotationEnum.CUSTOMER_ID.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_QUOTATION;
                break;
            case REFUND:
                customerAttr = RefundEnum.CUSTOMER_ID.getAttr();
                contractAttr = RefundEnum.CONTRACT_ID.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_REFUND;
                break;
            case PREPAYMENT_BALANCE:
                customerAttr = PaymentBalanceEnum.CUSTOMER_ID.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_PAYMENT_BALANCE;
                balance = true;
                break;
            default:
                return customerIdList;
        }
        List<String> fieldList = new ArrayList<>();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        List<Long> idList = new ArrayList<>();
        if(balance){
            fieldList.add("id");
            fieldList.add(customerAttr);
            boolQueryBuilder.filter(termsQuery(customerAttr,customerIdList));
            List<PaymentBalanceEntity> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum,boolQueryBuilder,PaymentBalanceEntity.class,fieldList);
            for (PaymentBalanceEntity paymentBalanceEntity : paasFormDataEntityList) {
                Long id = paymentBalanceEntity.getId();
                idList.add(id);
                customerMap.put(id,paymentBalanceEntity.getCustomerId());
            }
        }else {
            String customerDataAttr = StringConstant.JSON_DATA + StringConstant.POINT + customerAttr;
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            fieldList.add(customerDataAttr);
            if (!contractAttr.isEmpty()){
                String contractDataAttr = StringConstant.JSON_DATA + StringConstant.POINT + contractAttr;
                fieldList.add(contractDataAttr);
            }
            boolQueryBuilder.filter(termsQuery(customerDataAttr,customerIdList));
            List<PaasFormDataEntity> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum,boolQueryBuilder,PaasFormDataEntity.class,fieldList);
            for (PaasFormDataEntity entity : paasFormDataEntityList){
                idList.add(entity.getDataId());
                customerMap.put(entity.getDataId(),entity.getData().getLong(customerAttr));
                if (!contractAttr.isEmpty()){
                    contractMap.put(entity.getDataId(),entity.getData().getLong(contractAttr));
                }
            }
        }
        return idList;
    }

    private void updateContactTeam(List<Long> idList, String corpid, UserTeamEntity userTeamEntity, Map<Long, Long> customerMap) throws XbbException {
        if (idList.isEmpty()){
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.USER_ID),userTeamEntity.getUserId()));
        boolQueryBuilder.filter(termsQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.DATA_ID),idList));
        List<PaasFormDataEntity> contactUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Collections.singletonList(ContactTeamEnum.getAttrConnectData(ContactTeamEnum.DATA_ID)));
        List<ContactUserEntity> userTeamEntities = (List<ContactUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_CONTACT_TEAM, contactUserEntityList);
        List<ContactUserEntity> updateList = new ArrayList<>();
        for (ContactUserEntity entity :userTeamEntities){
            idList.remove(entity.getDataId());
            if (Objects.equals(entity.getIsMain(),0)){
                entity.setIsMain(1);
//                updateList.add(entity);
                contactUserModel.update(entity);
            }
        }
        List<ContactUserEntity> insertList = new ArrayList<>();
        if (!idList.isEmpty()){
            for (Long dataId : idList){
                ContactUserEntity contactUserEntity = new ContactUserEntity();
                BeanUtil.copyProperties(userTeamEntity,contactUserEntity);
                contactUserEntity.setId(null);
                contactUserEntity.setDataId(dataId);
                contactUserEntity.setCustomerId(customerMap.get(dataId));
                insertList.add(contactUserEntity);
            }
            contactUserModel.insertBatch(insertList, false);
        }
    }

    private void updateContractTeam(List<Long> idList, String corpid, UserTeamEntity userTeamEntity, Map<Long, Long> customerMap) throws XbbException {
        if (idList.isEmpty()){
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.USER_ID),userTeamEntity.getUserId()));
        boolQueryBuilder.filter(termsQuery(ContactTeamEnum.getEsAttr(ContactTeamEnum.DATA_ID), idList));
        List<PaasFormDataEntity> contractUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Collections.singletonList(ContactTeamEnum.getAttrConnectData(ContactTeamEnum.DATA_ID)));
        List<ContractUserEntity> userTeamEntities = (List<ContractUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_CONTRACT_TEAM, contractUserEntityList);
        List<ContactUserEntity> updateList = new ArrayList<>();
        for (ContractUserEntity entity :userTeamEntities){
            idList.remove(entity.getDataId());
            if (Objects.equals(entity.getIsMain(),0)){
                entity.setIsMain(1);
//                updateList.add(entity);
                contractUserModel.update(entity);
            }
        }
        List<ContractUserEntity> insertList = new ArrayList<>();
        if (!idList.isEmpty()){
            for (Long dataId : idList){
                ContractUserEntity contractUserEntity = new ContractUserEntity();
                BeanUtil.copyProperties(userTeamEntity,contractUserEntity);
                contractUserEntity.setId(null);
                contractUserEntity.setDataId(dataId);
                contractUserEntity.setCustomerId(customerMap.get(dataId));
                insertList.add(contractUserEntity);
            }
            contractUserModel.insertBatch(insertList, false);
        }
    }

    private void updateQuotationTeam(List<Long> idList, String corpid, UserTeamEntity userTeamEntity, Map<Long, Long> customerMap) throws XbbException {
        if (idList.isEmpty()){
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(QuotationTeamEnum.getEsAttr(QuotationTeamEnum.USER_ID), userTeamEntity.getUserId()));
        boolQueryBuilder.filter(termsQuery(QuotationTeamEnum.getEsAttr(QuotationTeamEnum.DATA_ID), idList));
        List<PaasFormDataEntity> quotationUserEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_QUOTATION_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Collections.singletonList(QuotationTeamEnum.getAttrConnectData(QuotationTeamEnum.DATA_ID)));
        List<QuotationUserEntity> userTeamEntities = (List<QuotationUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_QUOTATION_TEAM, quotationUserEntities);
        for (QuotationUserEntity entity :userTeamEntities){
            idList.remove(entity.getDataId());
            if (Objects.equals(entity.getIsMain(),0)){
                entity.setIsMain(1);
                quotationUserModel.update(entity);
            }
        }
        List<QuotationUserEntity> insertList = new ArrayList<>();
        if (!idList.isEmpty()){
            for (Long dataId : idList){
                QuotationUserEntity quotationUserEntity = new QuotationUserEntity();
                BeanUtil.copyProperties(userTeamEntity,quotationUserEntity);
                quotationUserEntity.setId(null);
                quotationUserEntity.setDataId(dataId);
                quotationUserEntity.setCustomerId(customerMap.get(dataId));
                insertList.add(quotationUserEntity);
            }
            quotationUserModel.insertBatch(insertList, false);
        }
    }

    private void updateOpportunityTeam(List<Long> idList, String corpid, UserTeamEntity userTeamEntity, Map<Long, Long> customerMap) throws XbbException {
        if (idList.isEmpty()){
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(OpportunityTeamEnum.getEsAttr(OpportunityTeamEnum.USER_ID), userTeamEntity.getUserId()));
        boolQueryBuilder.filter(termsQuery(OpportunityTeamEnum.getEsAttr(OpportunityTeamEnum.DATA_ID), idList));
        List<PaasFormDataEntity> opportunityUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Collections.singletonList(OpportunityTeamEnum.getAttrConnectData(OpportunityTeamEnum.DATA_ID)));
        List<OpportunityUserEntity> userTeamEntities = (List<OpportunityUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_OPPORTUNITY_TEAM, opportunityUserEntityList);
        List<OpportunityUserEntity> updateList = new ArrayList<>();
        for (OpportunityUserEntity entity : userTeamEntities){
            idList.remove(entity.getDataId());
            if (Objects.equals(entity.getIsMain(),0)){
                entity.setIsMain(1);
//                updateList.add(entity);
                opportunityUserModel.update(entity);
            }
        }
        List<OpportunityUserEntity> insertList = new ArrayList<>();
        if (!idList.isEmpty()){
            for (Long dataId : idList){
                OpportunityUserEntity opportunityUserEntity = new OpportunityUserEntity();
                BeanUtil.copyProperties(userTeamEntity,opportunityUserEntity);
                opportunityUserEntity.setId(null);
                opportunityUserEntity.setDataId(dataId);
                opportunityUserEntity.setCustomerId(customerMap.get(dataId));
                insertList.add(opportunityUserEntity);
            }
            opportunityUserModel.insertBatch(insertList, false);
        }
    }

    private void updatePaymentTeam(List<Long> idList, String corpid, UserTeamEntity userTeamEntity, Map<Long, Long> customerMap, Map<Long, Long> contractMap) throws XbbException {
        if (idList.isEmpty()){
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(PaymentTeamEnum.getEsAttr(PaymentTeamEnum.USER_ID),userTeamEntity.getUserId()));
        boolQueryBuilder.filter(termsQuery(PaymentTeamEnum.getEsAttr(PaymentTeamEnum.DATA_ID), idList));
        List<PaasFormDataEntity> paymentUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM,boolQueryBuilder, PaasFormDataEntity.class,Collections.singletonList(PaymentTeamEnum.getAttrConnectData(PaymentTeamEnum.DATA_ID)));
        List<PaymentUserEntity> userTeamEntities = (List<PaymentUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_SAAS_PAYMENT_TEAM, paymentUserEntityList);
        for (PaymentUserEntity entity :userTeamEntities){
            idList.remove(entity.getDataId());
            if (Objects.equals(entity.getIsMain(),0)){
                entity.setIsMain(1);
//                updateList.add(entity);
                paymentUserModel.update(entity);
            }
        }
        List<PaymentUserEntity> insertList = new ArrayList<>();
        if (!idList.isEmpty()){
            for (Long dataId : idList){
                PaymentUserEntity paymentUserEntity = new PaymentUserEntity();
                BeanUtil.copyProperties(userTeamEntity,paymentUserEntity);
                paymentUserEntity.setId(null);
                paymentUserEntity.setDataId(dataId);
                paymentUserEntity.setContractId(contractMap.get(dataId));
                paymentUserEntity.setCustomerId(customerMap.get(dataId));
                insertList.add(paymentUserEntity);
            }
            paymentUserModel.insertBatch(insertList);
        }
    }

    /**
     * 分配时更新预收款余额的团队
     * @param idList
     * @param corpid
     * @param userTeamEntity
     * @param customerMap
     * @throws XbbException
     */
    private void updatePaymentBalanceTeam(List<Long> idList, String corpid, UserTeamEntity userTeamEntity, Map<Long, Long> customerMap) throws XbbException {
        if (idList.isEmpty()){
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(PaymentBalanceTeamEnum.getEsAttr(PaymentBalanceTeamEnum.USER_ID),userTeamEntity.getUserId()));
        boolQueryBuilder.filter(termsQuery(PaymentBalanceTeamEnum.getEsAttr(PaymentBalanceTeamEnum.DATA_ID),idList));
        List<PaasFormDataEntity> paymentUserEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_PAYMENT_BALANCE_TEAM,boolQueryBuilder,PaasFormDataEntity.class,Collections.singletonList(PaymentBalanceTeamEnum.getAttrConnectData(PaymentBalanceTeamEnum.DATA_ID)));
        List<PaymentBalanceUserEntity> userTeamEntities = (List<PaymentBalanceUserEntity>) transferSubFormHelper.transferFormDataToUserTeamList(IndexTypeEnum.IDX_PAYMENT_BALANCE_TEAM, paymentUserEntityList);

        List<PaymentBalanceUserEntity> updateList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> updateIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaymentBalanceUserEntity entity :userTeamEntities){
            Long dataId = entity.getDataId();
            idList.remove(dataId);
            if (Objects.equals(entity.getIsMain(),0)){
                entity.setIsMain(1);
                updateList.add(entity);
                updateIdList.add(entity.getId());
            }
        }
        if(CollectionsUtil.isNotEmpty(updateList)){
            paymentBalanceUserModel.batchUpdateByUserIds(corpid,updateIdList,updateList,1,null);
        }
        List<PaymentBalanceUserEntity> insertList = new ArrayList<>();
        if (!idList.isEmpty()){
            for (Long dataId : idList){
                PaymentBalanceUserEntity paymentBalanceUserEntity = new PaymentBalanceUserEntity();
                BeanUtil.copyProperties(userTeamEntity,paymentBalanceUserEntity);
                paymentBalanceUserEntity.setId(null);
                paymentBalanceUserEntity.setDataId(dataId);
                paymentBalanceUserEntity.setCustomerId(customerMap.get(dataId));
                insertList.add(paymentBalanceUserEntity);
            }
            paymentBalanceUserModel.insertBatch(insertList);
        }
    }

    /**
     * 对用户团队的校验，团队成员改造的时候这个方法进行了大改造。
     *
     * @param validateDataDTO
     * @throws XbbException
     */
    @Override
    public void beforeVerifyUserTeam(ValidateDataDTO validateDataDTO) throws XbbException {
        teamUserHelp.beforeVerifyUserTeam(validateDataDTO);
    }


    @Override
    public void saveUserTeam(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo();
        if (Objects.nonNull(saasNeedRedundantAttrPoJo)) {
            BeforeSaveMyTeamDTO beforeSaveMyTeamDTO = saasNeedRedundantAttrPoJo.getBeforeSaveMyTeamDTO();
            beforeSaveMyTeamDTO.setDataId(saasFormSaveDTO.getNewPaasFormDataEntity().getId());
            UserTeamBatchSaveDTO userTeamBatchSaveDTO = beforeSaveMyTeam(beforeSaveMyTeamDTO);
            if (Objects.nonNull(userTeamBatchSaveDTO)) {
                LOG.info("登陆用户：" + Objects.isNull(userTeamBatchSaveDTO.getLoginUser()));
            }
            userTeamBatchSaveDTO.setIsCustomerNew(saasFormSaveDTO.getIsNew());
            // TODO 这里重新放下
            userTeamBatchSaveDTO.setLoginUser(saasFormSaveDTO.getLoginUser());
            saveMyTeam(userTeamBatchSaveDTO);

        }
    }

    @Override
    public void beforeWorkOrderUserTeam(ValidateDataDTO validateDataDTO) throws XbbException {
        TeamStrategy teamStrategy = teamDataFactory.getStrategy(validateDataDTO.getBusinessType(), validateDataDTO.getDistributorMark(), validateDataDTO.getSaasMark());
        TeamVerifyDTO teamVerifyDTO = new TeamVerifyDTO();
        BeanUtil.copyProperties(validateDataDTO, teamVerifyDTO);
        boolean isNew = Objects.isNull(validateDataDTO.getDataId()) || Objects.equals(validateDataDTO.getDataId(), 0L);
        String creatorId = StringUtil.isNotEmpty(validateDataDTO.getCreatorId()) ? validateDataDTO.getCreatorId() : validateDataDTO.getUserId();
        teamVerifyDTO.setFromDetail(false);
        teamVerifyDTO.setIsNew(isNew);
        teamVerifyDTO.setDataId(Collections.singletonList(validateDataDTO.getDataId()));
        teamVerifyDTO.setCreatorId(creatorId);
        teamVerifyDTO.setFromApproval(Objects.nonNull(validateDataDTO.getTaskId()));
        List<ReturnUserAndDepartmentPojo> ownerList = validateDataDTO.getOwnerIds();
        List<ReturnUserAndDepartmentPojo> coUserList = validateDataDTO.getCoUserId();
        Set<String> ownerIdList = new HashSet<>();
        Set<String> coUserIdList = new HashSet<>();
        if (CollectionsUtil.isNotEmpty(ownerList)) {
            ownerList.forEach(owner -> ownerIdList.add(Objects.toString(owner.getId(), "")));
        }
        if (CollectionsUtil.isNotEmpty(coUserList)) {
            coUserList.forEach(coUser -> coUserIdList.add(Objects.toString(coUser.getId(), "")));
        }

        //根据是否传工单负责人来判断是否是自由流程还是指定流程
        boolean ifFree = false;
        JSONObject data = validateDataDTO.getData();
        if (Objects.nonNull(data.get(WorkOrderEnum.MANAGER_ID.getAttr()))) {
            ifFree = true;
        }
        //自由流程和指定流程的负责人和协同人防重复处理不同处理
        if (ifFree) {
            ownerIdList.add(data.get(WorkOrderEnum.MANAGER_ID.getAttr()).toString());
        }

        teamVerifyDTO.setNewAddMainUserList(ownerIdList);
        teamVerifyDTO.setNewAddCoUserList(coUserIdList);
        TeamAfterVerifyDTO teamAfterVerifyDTO = teamStrategy.verify(teamVerifyDTO);
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = validateDataDTO.getSaasNeedRedundantAttrPoJo() == null ?
                new SaasNeedRedundantAttrPojo() : validateDataDTO.getSaasNeedRedundantAttrPoJo();
        saasNeedRedundantAttrPojo.setTeamAfterVerifyDTO(teamAfterVerifyDTO);
        List<TeamBatchPojo> teamBatchPojos = teamAfterVerifyDTO.getTeamBatchPojos();
        if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
            throw new XbbException(teamBatchPojos.get(0).getCode(), teamBatchPojos.get(0).getFailMsgReason());
        }
    }

    @Override
    public void batchAddUserTeam(BatchAddUserDTO batchAddUserDTO) throws XbbException{
        List<UserTeamEntity> userTeamEntities = batchAddUserDTO.getAddUserTeamEntities();
        Integer isMain = batchAddUserDTO.getIsMain();
        Map<String, List<Long>> userIdAndIdsMap = batchAddUserDTO.getUserIdAndIdsMap();
        Map<String, UserEntity> userEntityMap = batchAddUserDTO.getUserEntityMap();
        Map<Long, List<String>> idAndUserIdsMap = batchAddUserDTO.getIdAndUserIdsMap();
        Set<Long> dataIds = idAndUserIdsMap.keySet();
        Map<Long, PaasFormDataEntityExt> mainBusinessEntity = batchAddUserDTO.getMainBusinessEntity();
        Map<Long,String> idAnNameMap = batchAddUserDTO.getIdAndNameMap();
        Integer businessType = batchAddUserDTO.getBusinessType();
        String corpid = batchAddUserDTO.getCorpid();
        String loginUserId = batchAddUserDTO.getUserId();
        UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO = new UserTeamBatchAddByOtherBusinessDTO();
        BeanUtil.copyProperties(batchAddUserDTO, userTeamBatchAddByOtherBusinessDTO);
        userTeamBatchAddByOtherBusinessDTO.setIsMain(isMain);
        userTeamBatchAddByOtherBusinessDTO.setUserIdIn(new ArrayList<>(userIdAndIdsMap.keySet()));
        XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        List<Long> teamIds = new ArrayList<>(userTeamEntities.size());
        userTeamEntities.forEach(item -> teamIds.add(item.getId()));
        List<UpdateDataEntity> updateDataList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : userTeamEntities) {
            UpdateDataEntity updateDataEntity = new UpdateDataEntity();
            updateDataEntity.setCorpid(corpid);
            updateDataEntity.setId(userTeamEntity.getDataId());
            updateDataEntity.setUpdateTime(DateTimeUtil.getInt());
            updateDataList.add(updateDataEntity);
        }
        try {
            switch (refTypeEnum) {
                case CUSTOMER_MANAGEMENT:
                    List<CustomerUserEntity> customerUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, customerUserEntities, CustomerUserEntity.class, false);
                    customerUserModel.insertBatch(customerUserEntities, false);
                    List<Long> ids = new ArrayList<>(dataIds);
                    // 动态去除客户标签
                    boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
                    if (customerSeniorModel){
                        transferBackRuleScriptService.deletePublicSeniorTag(corpid,ids,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),batchAddUserDTO.getFormId());
                    }else {
                        customerRuleService.deletePublicTag(corpid, ids);
                    }
                    customerModel.updateBatch(updateDataList,corpid);
                    Runnable runnable = () -> {
                        try {
                            // 更新客户分配时间
                            proUpdateHelp.updateByIds(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), corpid, ids, CustomerManagementEnum.DISTRIBUTION_DATE.getAttr(), DateTimeUtil.getInt());
                            if (Objects.equals(isMain, BasicConstant.ONE)) {
                                // 如果添加负责人，则要更新redis中的捞取频次
                                for (Map.Entry<String, List<Long>> entry : userIdAndIdsMap.entrySet()) {
                                    String userId = entry.getKey();
                                    UserEntity userEntity = userEntityMap.getOrDefault(userId, new UserEntity());
                                    List<Long> idList = entry.getValue();
                                    customerRuleService.updateGainRateByIds(corpid, userEntity, idList);
                                }
                            }
                            // 联系人
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(ContactEnum.CUSTOMER_NAME.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            // 合同
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(ContractEnum.LINK_CUSTOMER.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            // 退货退款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.REFUND.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(RefundEnum.CUSTOMER_ID.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(RefundEnum.CONTRACT_ID.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setSourceBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(null);
                            // 回款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PaymentEnum.CUSTOMER.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(PaymentEnum.CONTRACT.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            // 用完销毁这个属性
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(null);
                            // 机会
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(SalesOpportunityEnum.CUSTOMER_NAME.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            // 报价单
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.QUOTATION.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(QuotationEnum.CUSTOMER_ID.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            // 预收款余额
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PaymentBalanceEnum.CUSTOMER_ID.getAttr());
                            addOtherBusinessTypeByCustomerId(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                        } catch (XbbException e) {
                            LOG.error("UserTeamService.batchAddUserTeam error businessType = " + businessType,e);
                        }
                    };
                    threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
                    break;
                case CONTRACT:
                    List<ContractUserEntity> contractUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, contractUserEntities, ContractUserEntity.class, false);
                    for (ContractUserEntity userEntity : contractUserEntities) {
                        PaasFormDataEntityExt contractEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(contractEntity.getData(), ContractEnum.LINK_CUSTOMER.getAttr(), 0L));
                    }
                    contractModel.updateBatch(updateDataList,corpid);
                    contractUserModel.insertBatch(contractUserEntities, false);
                    Runnable runnable1 = () -> {
                        try {
                            userTeamBatchAddByOtherBusinessDTO.setSourceBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
                            // 退货退款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.REFUND.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(RefundEnum.CONTRACT_ID.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(RefundEnum.CUSTOMER_ID.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                            // 回款
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PaymentEnum.CONTRACT.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(PaymentEnum.CUSTOMER.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                        } catch (XbbException e) {
                            LOG.error("listBatchService.handoverInsertUser error", e);
                        }
                    };
                    threadPoolBeanConfig.listBatchThreadPool().execute(runnable1);
                    break;
                case SALES_OPPORTUNITY:
                    List<OpportunityUserEntity> opportunityUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, opportunityUserEntities, OpportunityUserEntity.class, false);
                    for (OpportunityUserEntity userEntity : opportunityUserEntities) {
                        PaasFormDataEntityExt oppEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(oppEntity.getData(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), 0L));
                    }
                    opportunityModel.updateBatch(updateDataList,corpid);
                    opportunityUserModel.insertBatch(opportunityUserEntities, false);
                    break;
                case REFUND:
                    List<RefundUserEntity> refundUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, refundUserEntities, RefundUserEntity.class, false);
                    for (RefundUserEntity userEntity : refundUserEntities) {
                        PaasFormDataEntityExt refundEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(refundEntity.getData(), RefundEnum.CUSTOMER_ID.getAttr(), 0L));
                        userEntity.setContractId(FastJsonHelper.getLongOrDefaultFromFormData(refundEntity.getData(), RefundEnum.CONTRACT_ID.getAttr(), 0L));
                    }
                    refundModel.updateBatch(updateDataList,corpid);
                    refundUserModel.insertBatch(refundUserEntities, false);
                    break;
                case QUOTATION:
                    List<QuotationUserEntity> quotationUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, quotationUserEntities, QuotationUserEntity.class, false);
                    for (QuotationUserEntity userEntity : quotationUserEntities) {
                        PaasFormDataEntityExt quotationEntity = mainBusinessEntity.get(userEntity.getDataId());
                        userEntity.setCustomerId(FastJsonHelper.getLongOrDefaultFromFormData(quotationEntity.getData(), QuotationEnum.CUSTOMER_ID.getAttr(), 0L));
                    }
                    quotationModel.updateBatch(updateDataList,corpid);
                    quotationUserModel.insertBatch(quotationUserEntities, false);
                    break;
                case SUPPLIER:
                    List<SupplierUserEntity> supplierUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, supplierUserEntities, SupplierUserEntity.class, false);
                    supplierModel.updateBatch(updateDataList,corpid);
                    supplierUserModel.insertBatch(supplierUserEntities, false);
                    Runnable runnable2 = () -> {
                        try {
                            // 供应商联系人
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(SupplierContactEnum.SUPPLIER_ID.getAttr());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                        } catch (XbbException e) {
                            LOG.error("listBatchService.handoverInsertUser error", e);
                        }
                    };
                    threadPoolBeanConfig.listBatchThreadPool().execute(runnable2);
                    break;
                case PURCHASE:
                    List<PurchaseUserEntity> purchaseUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, purchaseUserEntities, PurchaseUserEntity.class, false);
                    purchaseModel.updateBatch(updateDataList,corpid);
                    purchaseUserModel.insertBatch(purchaseUserEntities, false);
                    Runnable runnable3 = () -> {
                        try {
                            // 付款计划
                            userTeamBatchAddByOtherBusinessDTO.setBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
                            userTeamBatchAddByOtherBusinessDTO.setRelyAttr(PayPlanEnum.LINK_PURCHASE.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setOtherRelyAttr(PayPlanEnum.LINK_SUPPLIER.getAttr());
                            userTeamBatchAddByOtherBusinessDTO.setSourceBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
                            addOtherBusinessType(userTeamBatchAddByOtherBusinessDTO, dataIds, userEntityMap);
                        } catch (XbbException e) {
                            LOG.error("listBatchService.handoverInsertUser error", e);
                        }
                    };
                    threadPoolBeanConfig.listBatchThreadPool().execute(runnable3);
                    break;
                case BOM_BILL:
                    List<BomUserEntity> bomUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, bomUserEntities, BomUserEntity.class, false);
                    bomBillModel.updateBatch(updateDataList,corpid);
                    bomUserModel.insertBatch(bomUserEntities, false);
                    break;
                case PRODUCTION_ORDER:
                    List<ProductionOrderUserEntity> orderUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, orderUserEntities, ProductionOrderUserEntity.class, false);
                    productionOrderModel.updateBatch(updateDataList,corpid);
                    productionOrderUserModel.insertBatch(orderUserEntities, false);
                    break;
                case WORK_ORDER:
                    List<WorkOrderFlowUserEntity> workOrderFlowUserEntityList = new ArrayList<>();
                    try {
                        BeanUtil.copyPropertiesList(userTeamEntities, workOrderFlowUserEntityList, WorkOrderFlowUserEntity.class, false);
                    } catch (Exception e) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                    workOrderModel.updateBatch(updateDataList,corpid);
                    workOrderFlowUserModel.insertBatch(workOrderFlowUserEntityList);
                    break;
                case CLUE:
                    List<ClueUserEntity> clueUserEntities = new ArrayList<>(userTeamEntities.size());
                    BeanUtil.copyPropertiesList(userTeamEntities, clueUserEntities, ClueUserEntity.class, false);
                    clueModel.updateBatch(updateDataList,corpid);
                    clueUserModel.insertBatch(clueUserEntities);
                    List<Long> idIn = new ArrayList<>(dataIds);
                    // 动态去除公海池标签
                    boolean cluePublicSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
                    if (cluePublicSeniorModel){
                        transferBackRuleScriptService.deletePublicSeniorTag(corpid,idIn,XbbRefTypeEnum.CLUE.getCode(),batchAddUserDTO.getFormId());
                    }else {
                        clueRuleService.deletePublicTag(corpid, idIn);
                    }
                    Runnable runnable4 = () -> {
                        try {
                            // 更新线索分配时间
                            proUpdateHelp.updateByIds(XbbRefTypeEnum.CLUE.getCode(), corpid, idIn, ClueEnum.DISTRIBUTION_DATE.getAttr(), DateTimeUtil.getInt());
                            if (Objects.equals(isMain, BasicConstant.ONE)) {
                                // 如果添加负责人，则要更新redis中的捞取频次
                                for (Map.Entry<String, List<Long>> entry : userIdAndIdsMap.entrySet()) {
                                    String userId = entry.getKey();
                                    UserEntity userEntity = userEntityMap.getOrDefault(userId, new UserEntity());
                                    List<Long> idList = entry.getValue();
                                    clueRuleService.updateGainRateByIds(corpid, userEntity, idList);
                                }
                            }
                        } catch (XbbException e) {
                            LOG.error("UserTeamService.batchAddUserTeam error businessType = " + businessType,e);
                        }
                    };
                    threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable4);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        UserTeamAddPushDTO userTeamAddPushDTO = new UserTeamAddPushDTO();
        BeanUtil.copyProperties(batchAddUserDTO, userTeamAddPushDTO);
        userTeamAddPushDTO.setIsMain(isMain);
        Runnable runnable = () -> {
            try {
                String memo = "";
                String saveName = "";
                String loginUserName = batchAddUserDTO.getLoginUserName();
                String xbbRefTypeName = XbbRefTypeEnum.getByCode(XbbRefTypeEnum.transferBusinessType4Distributor(businessType, batchAddUserDTO.getDistributorMark())).getName();
                for (Map.Entry<Long, List<String>> entry : idAndUserIdsMap.entrySet()) {
                    Long dataId = entry.getKey();
                    List<String> userIdIn = entry.getValue();
                    saveName = idAnNameMap.getOrDefault(dataId, "");

                    userTeamAddPushDTO.setDataId(dataId);
                    userTeamAddPushDTO.setUserIdIn(userIdIn);
                    pushMessageAfterAddUser(userTeamAddPushDTO);

                    String isMainStr = Objects.equals(isMain, BasicConstant.MAIN_USER) ? I18nMessageUtil.getMessage(ListBatchConstant.MAIN_USER_ALIAS) : I18nMessageUtil.getMessage(ListBatchConstant.CO_USER_ALIAS);
                    OperateModuleTypeEnum operateModuleTypeEnum = Objects.equals(isMain, BasicConstant.MAIN_USER) ? OperateModuleTypeEnum.RESPONSIBLE_TEAM : OperateModuleTypeEnum.COLLABORATIVE_TEAM;
                    List<String> userNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    userIdIn.forEach(user -> userNameList.add(userEntityMap.get(user).getName()));
                    String userNameListStr = StringUtils.join(userNameList, "，");

                    if(userIdIn.size() > BasicConstant.ONE){
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_ADD_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr);
                        List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        InfoArrPojo infoArrPojo = new InfoArrPojo();
                        infoArrPojo.setTitle(isMainStr);
                        infoArrPojo.setContent(userNameListStr);
                        infoArrPojoList.add(infoArrPojo);
                        mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, loginUserId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.NEW,
                                "", "", memo, batchAddUserDTO.getHttpHeader());
                    } else if(Objects.equals(userIdIn.size(), BasicConstant.ONE)){
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MAIN_USER), loginUserName, xbbRefTypeName, saveName, isMainStr, userNameListStr);
                        mongoLogHelp.buildLogWithoutAsync(corpid, loginUserId, loginUserName, operateModuleTypeEnum, OperateTypeEnum.NEW,
                                userIdIn.get(0), userNameListStr, memo, batchAddUserDTO.getHttpHeader());
                    }
                }
            } catch (XbbException e) {
                LOG.error("UserTeamService.batchAddUserTeam error",e);
            } catch (Exception e) {
                LOG.error("UserTeamService.batchAddUserTeam error",e);
            }
        };
        threadPoolBeanConfig.batchAddOrDelTeam().execute(runnable);
    }

    /**
     * 处理其它下游业务的团队的增加
     *
     * @param userTeamBatchAddByOtherBusinessDTO
     * @throws
     * @author long.rao
     * @date 2020-03-31 09:58
     */
    private void addOtherBusinessType(UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO, Collection<Long> dataIds, Map<String, UserEntity> userEntityMap) throws XbbException{
        String corpid = userTeamBatchAddByOtherBusinessDTO.getCorpid();
        String relyAttr = userTeamBatchAddByOtherBusinessDTO.getRelyAttr();
        String otherRelyAttr = userTeamBatchAddByOtherBusinessDTO.getOtherRelyAttr();
        Integer businessType = userTeamBatchAddByOtherBusinessDTO.getBusinessType();
        List<String> userIds = userTeamBatchAddByOtherBusinessDTO.getUserIdIn();
        if (CollectionsUtil.isEmpty(userIds)) {
            return;
        }
        Integer isMain = userTeamBatchAddByOtherBusinessDTO.getIsMain();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery("data."+ relyAttr + ".keyword", dataIds));
        List<String> fieldList = new ArrayList<>();
        fieldList.add(FieldTypeEnum.DATAID.getAlias());
        fieldList.add("data."+ relyAttr);
        if (Objects.nonNull(otherRelyAttr)) {
            fieldList.add("data." + otherRelyAttr);
        }
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        List<PaasFormDataEntityExt> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        // 主业务映射，
        Map<Long, Long> mainBusinessMap = new HashMap<>(paasFormDataList.size());
        Map<Long, Long> otherMainBusinessMap = new HashMap<>(paasFormDataList.size());
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataList) {
            mainBusinessMap.put(paasFormDataEntityExt.getDataId(), paasFormDataEntityExt.getData().getLong(relyAttr));
            if (Objects.nonNull(otherRelyAttr)) {
                Long otherRely = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), otherRelyAttr, 0L);
                otherMainBusinessMap.put(paasFormDataEntityExt.getDataId(), otherRely);
            }
        }
        if (mainBusinessMap.isEmpty()) {
            return;
        }
        IndexTypeEnum teamIndexType = indexTypeModel.getTeamIndexType(corpid, businessType);
        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexType, ParameterConstant.USER_ID), userIds));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexType, StringConstant.DATA_ID) , mainBusinessMap.keySet()));

        List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(teamIndexType, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexType, userTeamList);
        Map<String, UserTeamEntity> teamMap = new HashMap<>(teamList.size());
        teamList.forEach(userTeamEntity -> teamMap.put(userTeamEntity.getDataId() + StringConstant.COMMA + userTeamEntity.getUserId(), userTeamEntity));

        Set<UserTeamEntity> addUserTeams = new HashSet<>();
        Set<UserTeamEntity> updateUserTeams = new HashSet<>();
        Set<Long> teamIds = new HashSet<>();
        for (PaasFormDataEntityExt entityExt : paasFormDataList) {
            for (String userId : userIds) {
                String userKey = entityExt.getDataId() + StringConstant.COMMA + userId;
                if (!teamMap.containsKey(userKey)) {
                    UserEntity userEntity = userEntityMap.get(userId);
                    UserTeamEntity userTeamEntity = new UserTeamEntity();
                    initEntity(userTeamEntity, userEntity);
                    userTeamEntity.setIsMain(isMain);
                    userTeamEntity.setDataId(entityExt.getDataId());
                    addUserTeams.add(userTeamEntity);
                } else {
                    UserTeamEntity userTeamEntity = teamMap.get(userKey);
                    if (!Objects.equals(userTeamEntity.getIsMain(), BasicConstant.ONE) && Objects.equals(isMain, BasicConstant.ONE)) {
                        // 当添加负责人时，该人员作为协同人需要升级为负责人
                        userTeamEntity.setIsMain(BasicConstant.ONE);
                        updateUserTeams.add(userTeamEntity);
                        teamIds.add(userTeamEntity.getId());
                    }
                }
            }
        }
        if (!addUserTeams.isEmpty()) {
            batchAddUserTeams(businessType, userTeamBatchAddByOtherBusinessDTO.getSourceBusinessType(), new ArrayList<>(addUserTeams), mainBusinessMap, otherMainBusinessMap);
        }
        if (!updateUserTeams.isEmpty()) {
            updateUserTeam(businessType, new ArrayList<>(updateUserTeams), new ArrayList<>(teamIds), isMain, corpid);
        }
    }


    /**
     * 处理其它下游业务的团队的增加
     *
     * @param userTeamBatchAddByOtherBusinessDTO
     * @throws
     * @author long.rao
     * @date 2020-03-31 09:58
     */
    private void addOtherBusinessTypeByCustomerId(UserTeamBatchAddByOtherBusinessDTO userTeamBatchAddByOtherBusinessDTO, Collection<Long> dataIds, Map<String, UserEntity> userEntityMap) throws XbbException{
        String corpid = userTeamBatchAddByOtherBusinessDTO.getCorpid();
        String relyAttr = userTeamBatchAddByOtherBusinessDTO.getRelyAttr();
        Integer businessType = userTeamBatchAddByOtherBusinessDTO.getBusinessType();
        List<String> userIds = userTeamBatchAddByOtherBusinessDTO.getUserIdIn();
        if (CollectionsUtil.isEmpty(userIds)) {
            return;
        }
        Integer isMain = userTeamBatchAddByOtherBusinessDTO.getIsMain();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(relyAttr, dataIds));
        List<String> fieldList = new ArrayList<>();
        fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
        fieldList.add(relyAttr);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        List<PaymentBalanceEntity> paasFormDataList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaymentBalanceEntity.class, fieldList);
        // 主业务映射，
        Map<Long, Long> mainBusinessMap = new HashMap<>(paasFormDataList.size());
        paasFormDataList.forEach(paymentBalanceEntity -> {
            mainBusinessMap.put(paymentBalanceEntity.getId(), paymentBalanceEntity.getCustomerId());
        });
        if (mainBusinessMap.isEmpty()) {
            return;
        }
        IndexTypeEnum teamIndexType = indexTypeModel.getTeamIndexType(corpid, businessType);

        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexType, ParameterConstant.USER_ID), userIds));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexType, StringConstant.DATA_ID) , mainBusinessMap.keySet()));

        List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(teamIndexType, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexType, userTeamList);
        Map<String, UserTeamEntity> teamMap = new HashMap<>(teamList.size());
        teamList.forEach(userTeamEntity -> teamMap.put(userTeamEntity.getDataId() + StringConstant.COMMA + userTeamEntity.getUserId(), userTeamEntity));

        List<UserTeamEntity> addUserTeams = new ArrayList<>();
        List<UserTeamEntity> updateUserTeams = new ArrayList<>();
        List<Long> teamIds = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : paasFormDataList) {
            for (String userId : userIds) {
                String userKey = entityExt.getId() + StringConstant.COMMA + userId;
                if (!teamMap.containsKey(userKey)) {
                    UserEntity userEntity = userEntityMap.get(userId);
                    UserTeamEntity userTeamEntity = new UserTeamEntity();
                    initEntity(userTeamEntity, userEntity);
                    userTeamEntity.setIsMain(isMain);
                    userTeamEntity.setDataId(entityExt.getId());
                    addUserTeams.add(userTeamEntity);
                } else {
                    UserTeamEntity userTeamEntity = teamMap.get(userKey);
                    if (!Objects.equals(userTeamEntity.getIsMain(), BasicConstant.ONE) && Objects.equals(isMain, BasicConstant.ONE)) {
                        // 当添加负责人时，该人员作为协同人需要升级为负责人
                        userTeamEntity.setIsMain(BasicConstant.ONE);
                        updateUserTeams.add(userTeamEntity);
                        teamIds.add(userTeamEntity.getId());
                    }
                }
            }
        }
        if (!addUserTeams.isEmpty()) {
            batchAddUserTeams(businessType, XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), addUserTeams, mainBusinessMap, new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
        }
        if (!updateUserTeams.isEmpty()) {
            updateUserTeam(businessType, updateUserTeams, teamIds, isMain, corpid);
        }
    }

    /**
     * 批量新增团队
     *
     * @param businessType
     * @param sourceBusinessType
     * @param userTeamEntityList
     * @param mainIdMap
     * @param otherMainIdMap
     * @throws XbbException
     * @author long.rao
     * @date 2020-04-03 15:28
     */
    private void batchAddUserTeams(Integer businessType, Integer sourceBusinessType, List<UserTeamEntity> userTeamEntityList, Map<Long, Long> mainIdMap, Map<Long, Long> otherMainIdMap) throws XbbException{
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CONTRACT_TEAM:
                List<ContractUserEntity> contractUserEntities = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, contractUserEntities, ContractUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                for (ContractUserEntity entity : contractUserEntities) {
                    entity.setCustomerId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                }
                contractUserModel.insertBatch(contractUserEntities, false);
                break;
            case CONTACT_TEAM:
                List<ContactUserEntity> contactUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, contactUserEntityList, ContactUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                for (ContactUserEntity entity : contactUserEntityList) {
                    entity.setCustomerId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                }
                contactUserModel.insertBatch(contactUserEntityList, false);
                break;
            case OPPORTUNITY_TEAM:
                List<OpportunityUserEntity> opportunityUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, opportunityUserEntityList, OpportunityUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                for (OpportunityUserEntity entity : opportunityUserEntityList) {
                    entity.setCustomerId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                }
                opportunityUserModel.insertBatch(opportunityUserEntityList, false);
                break;
            case QUOTATION_TEAM:
                List<QuotationUserEntity> quotationUserEntities = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, quotationUserEntities, QuotationUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                for (QuotationUserEntity entity : quotationUserEntities) {
                    entity.setCustomerId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                }
                quotationUserModel.insertBatch(quotationUserEntities, false);
                break;
            case PAYMENT_TEAM:
                List<PaymentUserEntity> paymentUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, paymentUserEntityList, PaymentUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    for (PaymentUserEntity entity : paymentUserEntityList) {
                        entity.setCustomerId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                        entity.setContractId(otherMainIdMap.getOrDefault(entity.getDataId(), 0L));
                    }
                }
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                    for (PaymentUserEntity entity : paymentUserEntityList) {
                        entity.setContractId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                        entity.setCustomerId(otherMainIdMap.getOrDefault(entity.getDataId(), 0L));
                    }
                }
                paymentUserModel.insertBatch(paymentUserEntityList);
                break;
            case PAY_PLAN_TEAM:
                List<PayPlanUserEntity> payPlanUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, payPlanUserEntityList, PayPlanUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.SUPPLIER.getCode())) {
                    for (PayPlanUserEntity entity : payPlanUserEntityList) {
                        entity.setSupplierId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                        entity.setPurchaseId(otherMainIdMap.getOrDefault(entity.getDataId(), 0L));
                    }
                }
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.PURCHASE.getCode())) {
                    for (PayPlanUserEntity entity : payPlanUserEntityList) {
                        entity.setPurchaseId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                        entity.setSupplierId(otherMainIdMap.getOrDefault(entity.getDataId(), 0L));
                    }
                }
                payPlanUserModel.insertBatch(payPlanUserEntityList);
                break;
            case REFUND_TEAM:
                List<RefundUserEntity> refundUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, refundUserEntityList, RefundUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    for (RefundUserEntity entity : refundUserEntityList) {
                        entity.setCustomerId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                        entity.setContractId(otherMainIdMap.getOrDefault(entity.getDataId(), 0L));
                    }
                }
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                    for (RefundUserEntity entity : refundUserEntityList) {
                        entity.setContractId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                        entity.setCustomerId(otherMainIdMap.getOrDefault(entity.getDataId(), 0L));
                    }
                }
                refundUserModel.insertBatch(refundUserEntityList, false);
                break;
            case SUPPLIER_TEAM:
                List<SupplierUserEntity> supplierUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, supplierUserEntityList, SupplierUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                supplierUserModel.insertBatch(supplierUserEntityList, false);
                break;
            case SUPPLIER_CONTACT_TEAM:
                List<SupplierContactUserEntity> supplierContactUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, supplierContactUserEntityList, SupplierContactUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                for (SupplierContactUserEntity entity : supplierContactUserEntityList) {
                    entity.setSupplierId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                }
                supplierContactUserModel.insetBatch(supplierContactUserEntityList);
                break;
            case PURCHASE_TEAM:
                List<PurchaseUserEntity> purchaseUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, purchaseUserEntityList, PurchaseUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                purchaseUserModel.insertBatch(purchaseUserEntityList, false);
                break;
            case BOMBILL_TEAM:
                List<BomUserEntity> bomUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, bomUserEntityList, BomUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                bomUserModel.insertBatch(bomUserEntityList, false);
                break;
            case PRODUCTIONORDER_TEAM:
                List<ProductionOrderUserEntity> productionOrderUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, productionOrderUserEntityList, ProductionOrderUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                productionOrderUserModel.insertBatch(productionOrderUserEntityList, false);
                break;
            case WORK_ORDER_TEAM:
                List<WorkOrderFlowUserEntity> workOrderFlowUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, workOrderFlowUserEntityList, WorkOrderFlowUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                workOrderFlowUserModel.insertBatch(workOrderFlowUserEntityList);
                break;
            case PAYMENT_BALANCE_TEAM:
                List<PaymentBalanceUserEntity> paymentBalanceUserEntityList = new ArrayList<>();
                try {
                    BeanUtil.copyPropertiesList(userTeamEntityList, paymentBalanceUserEntityList, PaymentBalanceUserEntity.class, false);
                } catch (Exception e) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                }
                for (PaymentBalanceUserEntity entity : paymentBalanceUserEntityList) {
                    entity.setCustomerId(mainIdMap.getOrDefault(entity.getDataId(), 0L));
                }
                paymentBalanceUserModel.insertBatch(paymentBalanceUserEntityList);
                break;
            default:
                break;
        }
    }

    /**
     * 批量更新团队
     *
     * @param businessType
     * @param teamEntityList
     * @param dataIdIn
     * @param isMain
     * @param corpid
     * @throws XbbException
     * @author long.rao
     * @date 2020-04-03 15:28
     */
    private void updateUserTeam(Integer businessType, List<UserTeamEntity> teamEntityList, List<Long> dataIdIn, Integer isMain, String corpid) throws XbbException {
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                customerUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case CONTRACT_TEAM:
                contractUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case QUOTATION_TEAM:
                quotationUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case OPPORTUNITY_TEAM:
                opportunityUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case REFUND_TEAM:
                refundUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case CONTACT_TEAM:
                contactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case SUPPLIER_TEAM:
                supplierUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case SUPPLIER_CONTACT_TEAM:
                supplierContactUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case BOMBILL_TEAM:
                bomUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PRODUCTIONORDER_TEAM:
                productionOrderUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PURCHASE_TEAM:
                purchaseUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAYMENT_TEAM:
                paymentUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAYMENT_BALANCE_TEAM:
                paymentBalanceUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case PAY_PLAN_TEAM:
                payPlanUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            case WORK_ORDER_TEAM:
                workOrderFlowUserModel.batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, null);
                break;
            default:
                break;
        }
    }


    @Override
    public void handoverUpdateOwner(ChangeMainDTO changeMainDTO) throws XbbException {
        Integer businessType = changeMainDTO.getBusinessType();
        List<Long> dataIdList = changeMainDTO.getDataIdList();
        String userId = changeMainDTO.getChangeUserId();
        String corpid = changeMainDTO.getCorpid();
        XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (refTypeEnum) {
            case RETURNED_PURCHASE:
                returnedPurchaseModel.batchUpdateOwner(dataIdList, corpid, userId, WriteRequest.RefreshPolicy.NONE);
                break;
            case ASSEMBLE:
                assembleModel.batchUpdateOwner(dataIdList, corpid, userId, WriteRequest.RefreshPolicy.NONE);
                break;
            case TRANSFER:
                transferModel.batchUpdateOwner(dataIdList, corpid, userId, WriteRequest.RefreshPolicy.NONE);
                break;
            case INVENTORY:
                inventoryModel.batchUpdateOwner(dataIdList, corpid, userId, WriteRequest.RefreshPolicy.NONE);
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                instockModel.batchUpdateOwner(dataIdList, corpid, userId, WriteRequest.RefreshPolicy.NONE);
                break;
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case OUTSTOCK:
            case ORDER_OUTSTOCK:
                outstockModel.batchUpdateOwner(dataIdList, corpid, userId, WriteRequest.RefreshPolicy.NONE);
                break;
            case COST_ADJUST:
                costAdjustModel.batchUpdateOwner(dataIdList, corpid, userId, WriteRequest.RefreshPolicy.NONE);
                break;
            default:
                break;
        }
    }


    @Override
    public String canGainRate(CustomerRuleEntity rule, String corpid,
                                   UserEntity userEntity, Integer dataSize) throws XbbException {
        String errorMsg = "";
        //获取用户的每天的捞取、分配频次
        Integer num = StringUtil.toInt(paasRedisHelper.getValue(RedisPrefixConstant.CUSTOMER_GAIN_RATE, corpid + "_" + userEntity.getUserId()), null);
        if(num == null){
            CheckRuleGainRate checkRuleGainRate = new CheckRuleGainRate();
            num = checkRuleGainRate.getCustomerGainRateFromDB(rule, userEntity);
            if(num != null){
                Long endTime = DateTimeUtil.getTodayInt()+86400;
                Long now = DateTimeUtil.getInt();
                Long time = endTime - now;
                paasRedisHelper.setValue(RedisPrefixConstant.CUSTOMER_GAIN_RATE, corpid + "_" + userEntity.getUserId(), num, time.intValue());
            }
        }
        if(num == null){
            return errorMsg;
        }
        if (dataSize > num) {
            return I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_GAIN_RATE);
        }
        return errorMsg;
    }

    @Override
    public List<String> canGainPrePrincipal(CustomerRuleEntity rule, String corpid,
                            UserEntity userEntity, List<Long> dataIds, Map<Long, PaasFormDataEntityExt> entityExtMap, String operateStr) throws XbbException {

        String userId = userEntity.getUserId();

        List<Long> customerIds = new ArrayList<>(dataIds);

        Iterator<Long> iterator1 = customerIds.iterator();
        while (iterator1.hasNext()) {
            Long id = iterator1.next();
            PaasFormDataEntityExt customer = entityExtMap.getOrDefault(id, new PaasFormDataEntityExt());
            Integer isPublic = getIntegerOrDefaultFromFormData(customer.getData(), CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
            if (isPublic == 0) {
                // 非公海客户跳过这层校验
                iterator1.remove();
            }
        }

        //判断是否前负责人
        Map<String, Object> param = new HashMap<>(6);
        param.put("customerIdIn", customerIds);
        param.put("isMain", 1);
        param.put("corpid", corpid);
        param.put("userId", userId);
        // 因为有可能一个人员被多次变为前负责人，所以根据退回时间倒序拿最近的那条来判断
        param.put("orderByStr", "back_time desc");
        param.put("delIn", Arrays.asList(1,-1));
        List<CustomerUserEntity> customerUserList = customerUserModel.findEntitys(param);
        //为空不是前负责人
        Map<Long, CustomerUserEntity> customerUserMap = new HashMap<>();
        for (CustomerUserEntity entity : customerUserList) {
            Long dataId = entity.getDataId();
            CustomerUserEntity user = customerUserMap.get(dataId);
            if (Objects.isNull(user)) {
                customerUserMap.put(dataId, entity);
            }
        }
        /**
         * rule.getRuleType() 必然是 CustomerRuleEnum.PRE_PRINCIPAL_RULE.getCode()
         */
        IOperateRuleValue operateRuleValue = OperateRuleValueFactory.operateRuleValueFactory(rule.getRuleType());
        JSONArray ruleValueArray = (JSONArray) operateRuleValue.toObject(rule);

        CheckRulePrePrincipal checkRulePrePrincipal = new CheckRulePrePrincipal();

        Integer minValue = CheckRuleUtil.getMinValue(ruleValueArray, userEntity);

        Long now = DateTimeUtil.getInt();
        List<String> errorCustomerName = new ArrayList<>();
        Iterator<Long> iterator = customerIds.iterator();
        while (iterator.hasNext()) {
            Long customerId = iterator.next();
            CustomerUserEntity entity = customerUserMap.get(customerId);
            if (Objects.nonNull(entity) && Objects.nonNull(minValue)) {
                // 退回时间
                Long backTime = entity.getBackTime();
                Integer diffDay= DateTimeUtil.betweenDays(backTime,now);
                if(diffDay <= minValue){
                    PaasFormDataEntityExt entityExt = entityExtMap.getOrDefault(customerId, new PaasFormDataEntityExt());
                    String name = FastJsonHelper.getStringOrDefaultFromFormData(entityExt.getData(), CustomerManagementEnum.NAME.getAttr(), "");
                    errorCustomerName.add(name);
                    // 去锁
                    /*String key = corpid + "_" + customerId;
                    paasRedisHelper.removeValue(RedisPrefixConstant.CUSTOMER_LIST_BATCH,key);*/
                    dataIds.remove(customerId);
                }
            }
        }

        return errorCustomerName;
    }

    @Override
    public String canGainMaxNum(CustomerRuleEntity rule, String corpid,
                                    UserEntity userEntity, Map<Long, PaasFormDataEntityExt> entityExtMap) throws XbbException {
        String userId = userEntity.getUserId();
        Integer noBack = 1;
        Integer customerTypeBack = 2;
        Integer customerImportantDegreeBack = 3;

        IOperateRuleValue operateRuleValue = OperateRuleValueFactory.operateRuleValueFactory(rule.getRuleType());
        JSONObject ruleValueJson = (JSONObject) operateRuleValue.toObject(rule);

        //判断超过最大客户拥有数时是否允许捞取
        JSONObject backRuleJson = ruleValueJson.getJSONObject("backRule");
        Integer backType = backRuleJson.getInteger("backType");

        //根据客户状态自动退回     根据客户重要程度自动退回

        if(Objects.equals(backType, customerTypeBack) || Objects.equals(backType, customerImportantDegreeBack)){
            return "";
        }

        if(!Objects.equals(backType, noBack)){
            throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201032);
        }

        Integer type = ruleValueJson.getInteger("type");

        Integer contract = ruleValueJson.getInteger("contract");
        Integer opportunity = ruleValueJson.getInteger("opportunity");
        List<String> typeNotIn = JSON.parseArray(ruleValueJson.getJSONArray("customerStatus").toJSONString(), String.class);

        List<Long> labelNotIn = null;
        if (ruleValueJson.containsKey("label")) {
            labelNotIn = JSON.parseArray(ruleValueJson.getJSONArray("label").toJSONString(), Long.class);
        }

        List<Long> customerIdIn = new ArrayList<>(entityExtMap.keySet());
        Set<Long> excludeCustomerIdIn = new HashSet<>();
        // TODO 优化合同/机会检索数量
        excludeCustomerIdIn.addAll(checkRuleMaxCustomerNum.getExcludeCustomerIdInByContract(corpid, customerIdIn, contract));
        excludeCustomerIdIn.addAll(checkRuleMaxCustomerNum.getExcludeCustomerIdInByOpportunity(corpid, customerIdIn, opportunity));
        Map<Long, PaasFormDataEntityExt> customerMap = new HashMap<>(entityExtMap.size());
        for (Map.Entry<Long, PaasFormDataEntityExt> entry : entityExtMap.entrySet()){
            Long id = entry.getKey();
            PaasFormDataEntityExt entity = entry.getValue();
            if (excludeCustomerIdIn.contains(id)) {
                // 过滤有合同或者机会的客户
                continue;
            }
            String customerType = FastJsonHelper.getStringOrDefaultFromFormData(entity.getData(), CustomerManagementEnum.TYPE.getAttr(), "");
            if (Objects.nonNull(typeNotIn) && typeNotIn.contains(customerType)) {
                // 过滤某些状态不在规则处理中的客户
                continue;
            }

            String labelStr = entity.getData().getString(CustomerManagementEnum.LABEL.getAttr());
            List<Long> labels = JSON.parseArray(labelStr, Long.class);
            if (CollectionsUtil.isNotEmpty(labels) && CollectionsUtil.isNotEmpty(labelNotIn)) {
                labels.retainAll(labelNotIn);
                if (CollectionsUtil.isNotEmpty(labels)) {
                    // 有交集，这个客户需要去掉
                    continue;
                }
            }

            customerMap.put(id, entity);
        }

        StringBuilder errorMessage = new StringBuilder();

        if (Objects.equals(type, CustomerRuleChildEnum.LABEL.getCode())) {
            // 最大数量限制》根据客户标签设置
            Map<Long, Integer> minNumMap = checkRuleMaxCustomerNum.getMinDayMap(ruleValueJson.getJSONArray("restrict"), userEntity);
            Iterator<Map.Entry<Long, Integer>> iterator = minNumMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, Integer> next = iterator.next();
                Long key = next.getKey();
                if (labelNotIn.contains(key)) {
                    // 勾选的不退回的标签或当前线索的标签不一样的都去掉
                    iterator.remove();
                }
            }
            if (minNumMap.isEmpty()) {
                return "";
            }

            Integer del = 0;
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", del));
            // 团队表和客户表，联表查询
            IndexTypeEnum customerTeamIndex = indexTypeModel.getCustomerTeamIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
            HasChildQueryBuilder hasChildQueryBuilder = esHelper.teamQueryBuilder(customerTeamIndex, corpid, BasicConstant.ONE, Arrays.asList(userId));
            boolQueryBuilder.filter(hasChildQueryBuilder);
            if(typeNotIn != null && typeNotIn.size() > 0){
                boolQueryBuilder.filter(boolQuery().mustNot(termsQuery(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.TYPE), typeNotIn)));
            }
            if(labelNotIn != null && labelNotIn.size() > 0){
                boolQueryBuilder.filter(boolQuery().mustNot(termsQuery(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.LABEL), labelNotIn)));
            }
            boolQueryBuilder.filter(termsQuery(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.LABEL), minNumMap.keySet()));

            IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,customerIndex.getType()));
            sourceBuilder.query(boolQueryBuilder);
            List<String> fieldList = new ArrayList<>();
            fieldList.add(CustomerManagementEnum.getAttrConnectData(CustomerManagementEnum.LABEL));
            String[] strings = new String[fieldList.size()];
            sourceBuilder.fetchSource(fieldList.toArray(strings),null);
            SearchRequest searchRequest = new SearchRequest(customerIndex.getIndex());
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, 10000);
            searchRequest.source(sourceBuilder);
            XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);

            List<PaasFormDataEntityExt> content = esEntities.getContent();
            Map<Long, Integer> realLabelIdAndNum = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasFormDataEntityExt entityExt : content) {
                String labelStr = entityExt.getData().getString(CustomerManagementEnum.LABEL.getAttr());
                List<Long> labels = JSON.parseArray(labelStr, Long.class);
                if (CollectionsUtil.isEmpty(labels)) {
                    continue;
                }
                for (Long label : labels) {
                    Integer num = realLabelIdAndNum.get(label);
                    if (Objects.isNull(num)) {
                        num = 1;
                    } else {
                        num++;
                    }
                    realLabelIdAndNum.put(label, num);
                }
            }
            Map<Long, Integer> dataLabelIdAndNum = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (Map.Entry<Long, PaasFormDataEntityExt> extEntry: entityExtMap.entrySet()) {
                PaasFormDataEntityExt value = extEntry.getValue();
                String labelStr = value.getData().getString(CustomerManagementEnum.LABEL.getAttr());
                List<Long> labels = JSON.parseArray(labelStr, Long.class);
                if (CollectionsUtil.isNotEmpty(labels)) {
                    for (Long label : labels) {
                        Integer num = dataLabelIdAndNum.get(label);
                        if (Objects.isNull(num)) {
                            num = 1;
                        } else {
                            num++;
                        }
                        dataLabelIdAndNum.put(label, num);
                    }
                }
            }
            for (Map.Entry<Long, Integer> entry : minNumMap.entrySet()) {
                Long key = entry.getKey();
                Integer value = entry.getValue();
                Integer realNum = realLabelIdAndNum.getOrDefault(key, 0);
                Integer dataNum = dataLabelIdAndNum.getOrDefault(key, 0);
                int subNum = realNum + dataNum;
                if (subNum > value) {
                    // 超过拥有最大数
                    errorMessage.append(I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_MAX_RULE));
                    break;
                }

            }
            return errorMessage.toString();

        }

        //获取当前用户的最大配置
        /**
         * key:value
         * {"1":2,"2":6,"3":5}
         */
        JSONObject minObject = checkRuleMaxCustomerNum.getMinObject(ruleValueJson.getJSONArray("restrict"), userEntity, type);
        if (minObject.isEmpty()) {
            return "";
        }

        Set<String> keySet = minObject.keySet();
        if (keySet.contains("0")) {
            // 最大数量限制》所有客户统一设置
            // 这里是所有客户统一设置
            Integer minValue = minObject.getInteger("0");
            Integer customerCount = checkRuleMaxCustomerNum.getCustomerCount(corpid, userEntity.getUserId(), typeNotIn, labelNotIn, contract, opportunity, 0);
            customerCount += customerMap.size();
            if (customerCount > minValue) {
                return I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_MAX_RULE);
            }
            return "";
        }
        // 最大数量限制》根据客户重要程度设置
        Set<Integer> degrees = new HashSet<>();
        Map<String, Integer> degreeCountNum = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt entityExt : customerMap.values()) {
            String degree = FastJsonHelper.getStringOrDefaultFromFormData(entityExt.getData(), CustomerManagementEnum.IMPORTANT_DEGREE.getAttr(), String.valueOf(StarEnum.ZERO.getValue()));
            Integer count = degreeCountNum.getOrDefault(degree, 0);
            count++;
            degreeCountNum.put(degree, count);
            degrees.add(Integer.valueOf(degree));
        }
        if (degrees.contains(1) && !degrees.contains(0)) {
            // 如果选了一星，那么也要把零星加上，因为这个规则代表一星及以下
            degrees.add(0);
        }
        if (degrees.contains(0) && !degrees.contains(1)) {
            // 如果选了一星，那么也要把零星加上，因为这个规则代表一星及以下
            degrees.add(1);
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        checkRuleMaxCustomerNum.getCustomerUserIdIn(corpid, userId, contract, opportunity, boolQueryBuilder);
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        if(typeNotIn != null && typeNotIn.size() > 0){
            boolQueryBuilder.mustNot(termsQuery("data." + CustomerManagementEnum.TYPE.getAttr(), typeNotIn));
        }
        if (labelNotIn != null && labelNotIn.size() > 0) {
            boolQueryBuilder.filter(termsQuery(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.LABEL), labelNotIn));
        }
        boolQueryBuilder.filter(termsQuery(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.IMPORTANT_DEGREE), degrees));

        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("aggs01").field(CustomerManagementEnum.getEsAttr4Keyword(CustomerManagementEnum.IMPORTANT_DEGREE));
        termsAggregationBuilder.size(SizeConstant.TERM_AGG_MAX_BUCKETS);
        termsAggregationBuilder.executionHint(ElasticConstant.EXECUTION_HINT);
        IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(customerIndex, boolQueryBuilder, termsAggregationBuilder);
        JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
        Map<Integer, Integer> dataMap = new HashMap<>(bucketsArray.size());
        for (Object object : bucketsArray) {
            if (object != null) {
                JSONObject dataJsonObject = (JSONObject) object;
                Integer key = dataJsonObject.getInteger("key");
                dataMap.put(key, dataJsonObject.getInteger("doc_count"));
            }
        }
        if (degreeCountNum.containsKey("0")) {
            // 一星这里需要把零星也加上
            Integer integer = degreeCountNum.get("0");
            Integer integer1 = degreeCountNum.getOrDefault("1", 0);
            integer1 += integer;
            degreeCountNum.put("1", integer1);
            degreeCountNum.remove("0");
        }

        for(String key : degreeCountNum.keySet()){
            Integer minValue = minObject.getInteger(key);
            Integer degree = Integer.valueOf(key);
            Integer count = dataMap.getOrDefault(degree, 0);
            Integer num = degreeCountNum.getOrDefault(key, 0);
            if (Objects.equals(degree, 1)) {
                // 一星这里需要把零星也加上
                Integer count1 = dataMap.getOrDefault(0, 0);
                count += count1;
            }
            count += num;
            if (count > minValue) {
                errorMessage.append(I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_MAX_RULE));
                break;
            }

        }
        return errorMessage.toString();
    }

    @Override
    public String canGainClueRate(ClueRuleEntity rule, String corpid,
                                  UserEntity userEntity, Integer dataSize) throws XbbException {
        String errorMsg = "";
        //获取用户的每天的捞取、分配频次
        Integer num = StringUtil.toInt(paasRedisHelper.getValue(RedisPrefixConstant.CLUE_GAIN_RATE, corpid + "_" + userEntity.getUserId()), null);
        if(num == null){
            CheckClueRuleGainRate checkRuleGainRate = new CheckClueRuleGainRate();
            num = checkRuleGainRate.getClueGainRateFromDB(rule, userEntity);
            if(num != null){
                Long endTime = DateTimeUtil.getTodayInt()+86400;
                Long now = DateTimeUtil.getInt();
                Long time = endTime - now;
                paasRedisHelper.setValue(RedisPrefixConstant.CLUE_GAIN_RATE, corpid + "_" + userEntity.getUserId(), num, time.intValue());
            }
        }
        if(num == null){
            return errorMsg;
        }
        if (dataSize > num) {
            return I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_GAIN_CLUE_RATE);
        }
        return errorMsg;
    }

    @Override
    public List<String> canGainCluePrePrincipal(ClueRuleEntity rule, String corpid,
                                            UserEntity userEntity, List<Long> dataIds, Map<Long, PaasFormDataEntityExt> entityExtMap, String operateStr) throws XbbException {

        String userId = userEntity.getUserId();

        List<Long> clueIds = new ArrayList<>(dataIds);

        Iterator<Long> iterator1 = clueIds.iterator();
        while (iterator1.hasNext()) {
            Long id = iterator1.next();
            PaasFormDataEntityExt customer = entityExtMap.getOrDefault(id, new PaasFormDataEntityExt());
            Integer isPublic = getIntegerOrDefaultFromFormData(customer.getData(), ClueEnum.IS_PUBLIC.getAttr(), 0);
            if (isPublic == 0) {
                // 非公海线索跳过这层校验
                iterator1.remove();
            }
        }

        //判断是否前负责人
        Map<String, Object> param = new HashMap<>(6);
        param.put("dataIdIn", clueIds);
        param.put("isMain", 1);
        param.put("corpid", corpid);
        param.put("userId", userId);
        param.put("orderByStr", "back_time desc");
        param.put("del", -1);
        List<ClueUserEntity> clueUserEntities = clueUserModel.findEntitys(param);
        //为空不是前负责人
        Map<Long, ClueUserEntity> clueUserMap = new HashMap<>();
        for (ClueUserEntity entity : clueUserEntities) {
            Long dataId = entity.getDataId();
            ClueUserEntity user = clueUserMap.get(dataId);
            if (Objects.isNull(user)) {
                clueUserMap.put(dataId, entity);
            }
        }
        /**
         * rule.getRuleType() 必然是 ClueRuleEnum.PRE_PRINCIPAL_RULE.getCode()
         */
        IOperateClueRuleValue operateRuleValue = OperateClueRuleValueFactory.operateRuleValueFactory(rule.getRuleType());
        JSONArray ruleValueArray = (JSONArray) operateRuleValue.toObject(rule);

        CheckClueRulePrePrincipal checkRulePrePrincipal = new CheckClueRulePrePrincipal();

        Integer minValue = CheckRuleUtil.getMinValue(ruleValueArray, userEntity);

        Long now = DateTimeUtil.getInt();
        List<String> errorClueName = new ArrayList<>();
        Iterator<Long> iterator = clueIds.iterator();
        while (iterator.hasNext()) {
            Long clueId = iterator.next();
            ClueUserEntity entity = clueUserMap.get(clueId);
            if (Objects.nonNull(entity) && Objects.nonNull(minValue)) {
                // 退回时间
                Long backTime = entity.getBackTime();
                Integer diffDay= DateTimeUtil.betweenDays(backTime,now);
                if(diffDay <= minValue){
                    PaasFormDataEntityExt entityExt = entityExtMap.getOrDefault(clueId, new PaasFormDataEntityExt());
                    String name = FastJsonHelper.getStringOrDefaultFromFormData(entityExt.getData(), ClueEnum.COMPANY_NAME.getAttr(), "");
                    errorClueName.add(name);
                    dataIds.remove(clueId);
                }
            }
        }
        return errorClueName;
    }

    @Override
    public String canGainMaxClueNum(ClueRuleEntity rule, String corpid,
                                UserEntity userEntity, Map<Long, PaasFormDataEntityExt> entityExtMap) throws XbbException {
        String userId = userEntity.getUserId();
        Integer noBack = 1;
        Integer clueTypeBack = 2;

        IOperateClueRuleValue operateRuleValue = OperateClueRuleValueFactory.operateRuleValueFactory(rule.getRuleType());
        JSONObject ruleValueJson = (JSONObject) operateRuleValue.toObject(rule);

        //判断超过最大拥有数时是否允许捞取
        JSONObject backRuleJson = ruleValueJson.getJSONObject("backRule");
        Integer backType = backRuleJson.getInteger("backType");


        if(Objects.equals(backType, clueTypeBack)){
            return "";
        }

        if(!Objects.equals(backType, noBack)){
            throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201032);
        }

        Integer type = ruleValueJson.getInteger("type");


        List<String> typeNotIn = JSON.parseArray(ruleValueJson.getJSONArray("clueStatus").toJSONString(), String.class);

        List<Long> labelNotIn = JSON.parseArray(ruleValueJson.getJSONArray("label").toJSONString(), Long.class);



        Map<Long, PaasFormDataEntityExt> clueMap = new HashMap<>(entityExtMap.size());
        for (Map.Entry<Long, PaasFormDataEntityExt> entry : entityExtMap.entrySet()){
            Long id = entry.getKey();
            PaasFormDataEntityExt entity = entry.getValue();

            String status = FastJsonHelper.getStringOrDefaultFromFormData(entity.getData(), ClueEnum.CLUE_STATUS.getAttr(), "");
            if (Objects.nonNull(typeNotIn) && typeNotIn.contains(status)) {
                // 过滤某些状态不在规则处理中的线索
                continue;
            }

            String labelStr = entity.getData().getString(ClueEnum.LABEL.getAttr());
            List<Long> labels = JSON.parseArray(labelStr, Long.class);
            if (CollectionsUtil.isNotEmpty(labels) && CollectionsUtil.isNotEmpty(labelNotIn)) {
                labels.retainAll(labelNotIn);
                if (CollectionsUtil.isNotEmpty(labels)) {
                    // 有交集，需要去掉
                    continue;
                }
            }

            clueMap.put(id, entity);
        }

        StringBuilder errorMessage = new StringBuilder();
        if (Objects.equals(type, ClueRuleChildEnum.LABEL.getCode())) {

            Map<Long, Integer> minNumMap = checkRuleMaxClueNum.getMinDayMap(ruleValueJson.getJSONArray("restrict"), userEntity);
            Iterator<Map.Entry<Long, Integer>> iterator = minNumMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, Integer> next = iterator.next();
                Long key = next.getKey();
                if (labelNotIn.contains(key)) {
                    // 勾选的不退回的标签或当前线索的标签不一样的都去掉
                    iterator.remove();
                }
            }
            if (minNumMap.isEmpty()) {
                return "";
            }
            //TODO 本次查询应该可以和下面那次合并，需要梳理逻辑
            Integer del = 0;
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("del", del));
            HasChildQueryBuilder hasChildQueryBuilder = esHelper.teamQueryBuilder(IndexTypeEnum.IDX_SAAS_CLUE_TEAM, corpid, BasicConstant.ONE, Arrays.asList(userId));
            boolQueryBuilder.filter(hasChildQueryBuilder);
            if(typeNotIn != null && typeNotIn.size() > 0){
                boolQueryBuilder.filter(boolQuery().mustNot(termsQuery("data." + ClueEnum.CLUE_STATUS.getAttr(), typeNotIn)));
            }
            if(labelNotIn != null && labelNotIn.size() > 0){
                boolQueryBuilder.filter(boolQuery().mustNot(termsQuery(ClueEnum.getEsAttr4Keyword(ClueEnum.LABEL), labelNotIn)));
            }
            boolQueryBuilder.filter(termsQuery(ClueEnum.getEsAttr4Keyword(ClueEnum.LABEL), minNumMap.keySet()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_CLUE.getType()));

            //拿固定数据
            List<String> fieldList = new ArrayList<>();
            fieldList.add(ClueEnum.getAttrConnectData(ClueEnum.LABEL));
            String[] strings = new String[fieldList.size()];
            sourceBuilder.fetchSource(fieldList.toArray(strings),null);
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CLUE.getIndex());
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 10000);
            searchRequest.source(sourceBuilder);
            XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);

            List<PaasFormDataEntityExt> content = esEntities.getContent();
            Map<Long, Integer> realLabelIdAndNum = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasFormDataEntityExt entityExt : content) {
                String labelStr = entityExt.getData().getString(ClueEnum.LABEL.getAttr());
                List<Long> labels = JSON.parseArray(labelStr, Long.class);
                if (CollectionsUtil.isEmpty(labels)) {
                    continue;
                }
                for (Long label : labels) {
                    Integer num = realLabelIdAndNum.get(label);
                    if (Objects.isNull(num)) {
                        num = 1;
                    } else {
                        num++;
                    }
                    realLabelIdAndNum.put(label, num);
                }
            }
            Map<Long, Integer> dataLabelIdAndNum = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (Map.Entry<Long, PaasFormDataEntityExt> extEntry: clueMap.entrySet()) {
                Long key = extEntry.getKey();
                PaasFormDataEntityExt value = extEntry.getValue();
                String labelStr = value.getData().getString(ClueEnum.LABEL.getAttr());
                List<Long> labels = JSON.parseArray(labelStr, Long.class);
                if (CollectionsUtil.isEmpty(labels)) {
                    continue;
                }
                for (Long label : labels) {
                    Integer num = dataLabelIdAndNum.get(label);
                    if (Objects.isNull(num)) {
                        num = 1;
                    } else {
                        num++;
                    }
                    dataLabelIdAndNum.put(label, num);
                }
            }
            for (Map.Entry<Long, Integer> entry : minNumMap.entrySet()) {
                Long key = entry.getKey();
                Integer value = entry.getValue();
                Integer realNum = realLabelIdAndNum.getOrDefault(key, 0);
                Integer dataNum = dataLabelIdAndNum.getOrDefault(key, 0);
                Integer subNum = realNum + dataNum;
                if (subNum > value) {
                    // 超过拥有线索最大数
                    errorMessage.append(I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_MAX_CLUE_RULE));
                    break;
                }

            }
            return errorMessage.toString();

        }

        //获取当前用户的最小配置
        JSONObject minObject = checkRuleMaxClueNum.getMinObject(ruleValueJson.getJSONArray("restrict"), userEntity, type);
        if (minObject.isEmpty()) {
            return "";
        }
        if (Objects.equals(type, ClueRuleChildEnum.ALL.getCode())) {
            Integer minValue = minObject.getInteger("0");
            Integer clueCount = checkRuleMaxClueNum.getClueCount(corpid, userEntity.getUserId(), typeNotIn, labelNotIn, "0");
            clueCount += clueMap.size();
            if (clueCount > minValue) {
                return I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_MAX_CLUE_RULE);
            }
            return "";
        }

        Map<String, Integer> dataMap = new HashMap<>(DEFAULT_INITIAL_CAPACITY);
        for (Map.Entry<Long, PaasFormDataEntityExt> entry : clueMap.entrySet()) {
            String status = FastJsonHelper.getStringOrDefaultFromFormData(entry.getValue().getData(), ClueEnum.CLUE_STATUS.getAttr(), "");
            if (StringUtil.isEmpty(status)) {
                continue;
            }
            Integer num = dataMap.get(status);
            if (Objects.isNull(num)) {
                num = 1;
            } else {
                num++;
            }
            dataMap.put(status, num);
        }
        if (dataMap.isEmpty()) {
            return "";
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        HasChildQueryBuilder hasChildQueryBuilder = esHelper.teamQueryBuilder(IndexTypeEnum.IDX_SAAS_CLUE_TEAM, corpid, BasicConstant.ONE, Arrays.asList(userId));
        boolQueryBuilder.filter(hasChildQueryBuilder);
        boolQueryBuilder.filter(termsQuery(ClueEnum.getEsAttr4Keyword(ClueEnum.CLUE_STATUS), dataMap.keySet()));

        ValuesSourceAggregationBuilder valuesSourceAggregationBuilder = AggregationBuilders.terms("aggs01").field(ClueEnum.getEsAttr4Keyword(ClueEnum.CLUE_STATUS));
        ((TermsAggregationBuilder) valuesSourceAggregationBuilder).size(Integer.MAX_VALUE);
        JSONObject resultJsonObject = esHelper.elasticAggs4Buckets2Object(IndexTypeEnum.IDX_SAAS_CLUE, boolQueryBuilder, valuesSourceAggregationBuilder);
        JSONArray bucketsArray = resultJsonObject.getJSONArray("buckets");
        Map<String, Integer> map = new HashMap<>(bucketsArray.size());
        for (Object object : bucketsArray) {
            if (object != null) {
                JSONObject dataJsonObject = (JSONObject) object;
                String key = dataJsonObject.getString("key");
                map.put(key, dataJsonObject.getInteger("doc_count"));
            }
        }


        for(String key : dataMap.keySet()){
            Integer minValue = minObject.getInteger(key);
            Integer count = dataMap.getOrDefault(key, 0);
            Integer num = map.getOrDefault(key, 0);
            count += num;
            if (count > minValue) {
                errorMessage.append(I18nMessageUtil.getMessage(ListBatchConstant.OUTNUMBER_FOR_MAX_CLUE_RULE));
                break;
            }

        }
        return errorMessage.toString();
    }


    /**
     * 修复回款单/付款单的负责人数据
     * @param corpid
     * @param businessTypeEnum
     * @param paasFormDataList
     * @throws XbbException
     */
    @Override
    public void scriptUserTeamBySheetBusiness(String corpid, XbbRefTypeEnum businessTypeEnum,List<PaasFormDataEntityExt> paasFormDataList) throws XbbException {
        Integer businessType = businessTypeEnum.getCode();
        List<Long> otherBusinessIdIn = new ArrayList<>();
        Map<Long, List<Long>> sheetIdAndCustomerIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<Long>> sheetIdAndContractIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> replyCustomerIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> replyContractIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> prepayList = SheetTypeEnum.belongPrepay(businessTypeEnum);
        List<String> otherList = SheetTypeEnum.belongOther(businessTypeEnum);
        for ( PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataList ) {
            Long dataId = paasFormDataEntityExt.getId();
            otherBusinessIdIn.add(dataId);
            JSONObject data = paasFormDataEntityExt.getData();
            String type = FastJsonHelper.getStringOrDefaultFromFormData(data,PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(),"0");
            if ( prepayList.contains(type) ){
                List<Long> dataIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                switch (businessTypeEnum) {
                    case PAY_SHEET:
                        Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(data,PaySheetEnum.LINK_SUPPLIER.getAttr(),0L);
                        replyCustomerIds.add(supplierId);
                        dataIds.add(supplierId);
                        break;
                    case PAYMENT_SHEET:
                        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data,PaymentSheetEnum.CUSTOMER_ID.getAttr(),0L);
                        replyCustomerIds.add(customerId);
                        dataIds.add(customerId);
                        break;
                    default:
                        break;
                }
                sheetIdAndCustomerIdMap.put(dataId,dataIds);
            } else if ( otherList.contains(type) ) {
                List<Long> dataIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                JSONArray contractIdArr = new JSONArray();
                switch (businessTypeEnum) {
                    case PAY_SHEET:
                        try {
                            contractIdArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data,PaySheetEnum.LINK_PURCHASE.getAttr(),new JSONArray());
                        } catch (Exception e) {
                            LOG.error("付款单获取关联采购合同错误,错误数据为：" + paasFormDataEntityExt.getId() +"\n数据体为："+ data ,e);
                            LOG.error("付款单获取关联采购合同错误",e);
                            contractIdArr = new JSONArray();
                        }
                        break;
                    case PAYMENT_SHEET:
                        try {
                            contractIdArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data,PaymentSheetEnum.CONTRACT.getAttr(),new JSONArray());
                        } catch (Exception e) {
                            LOG.error("回款单获取关联合同错误,错误数据为：" +paasFormDataEntityExt.getId() +"\n数据体为："+ data ,e);
                            LOG.error("回款单获取关联合同错误",e);
                            contractIdArr = new JSONArray();
                        }
                        break;
                    default:
                        break;
                }
                for ( Object contractIdObj : contractIdArr ) {
                    if ( Objects.nonNull(contractIdObj) ) {
                        dataIds.add(Long.valueOf(contractIdObj.toString()));
                        replyContractIds.add(Long.valueOf(contractIdObj.toString()));
                    }
                }
                sheetIdAndContractIdMap.put(dataId,dataIds);
            }
        }
        if ( otherBusinessIdIn.isEmpty() ) {
            return;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //取到所有本次相关数据(合同/客户、采购合同/供应商)的团队负责人,数据源团队
        Map<Long, UserTypePojo> sourceCustomerMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if ( CollectionsUtil.isNotEmpty(replyCustomerIds) ){
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_SAAS_SUPPLIER;
            switch (businessTypeEnum) {
                case PAYMENT_SHEET:
                    indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
                    break;
                case PAY_SHEET:
                    indexTypeEnum = IndexTypeEnum.IDX_SAAS_SUPPLIER;
                    break;
                default:
                    break;
            }
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(indexTypeEnum, StringConstant.DATA_ID), replyCustomerIds));
            List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntity.class, null);
            List<UserTeamEntity> sourceCustomerTeamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(indexTypeEnum, userTeamList);
            //回款单/付款单id，下关联的合同/客户、采购合同/供应商的负责人/协同人
            sourceCustomerMap = getSetUserTeamEntityMap(sourceCustomerTeamEntityList,sheetIdAndCustomerIdMap);
        }
        Map<Long, UserTypePojo> sourceContractMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if ( CollectionsUtil.isNotEmpty(replyContractIds) ){
            UserTeamEnum sourceUserTeamEnum = UserTeamEnum.getByCode(XbbRefTypeEnum.PURCHASE.getCode());
            switch (businessTypeEnum) {
                case PAYMENT_SHEET:
                    sourceUserTeamEnum = UserTeamEnum.getByCode(XbbRefTypeEnum.CONTRACT.getCode());
                    break;
                case PAY_SHEET:
                    sourceUserTeamEnum = UserTeamEnum.getByCode(XbbRefTypeEnum.PURCHASE.getCode());
                    break;
                default:
                    break;
            }
            boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(sourceUserTeamEnum.getIndexTypeEnum(), StringConstant.DATA_ID), replyContractIds));
            List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(sourceUserTeamEnum.getIndexTypeEnum(), boolQueryBuilder, PaasFormDataEntity.class, null);
            List<UserTeamEntity> sourceContractTeamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(sourceUserTeamEnum.getIndexTypeEnum(), userTeamList);
            //回款单/付款单id，下关联的合同/客户、采购合同/供应商的负责人/协同人
            sourceContractMap = getSetUserTeamEntityMap(sourceContractTeamEntityList,sheetIdAndContractIdMap);
        }

        //回款单/付款单现有的团队
        IndexTypeEnum teamIndexType = indexTypeModel.getTeamIndexType(corpid, businessType);

        boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(teamIndexType, StringConstant.DATA_ID), otherBusinessIdIn));
        List<PaasFormDataEntity> userTeamList = esHelper.findByScroll(teamIndexType, boolQueryBuilder, PaasFormDataEntity.class, null);
        List<UserTeamEntity> teamEntityList = (List<UserTeamEntity>) transferSubFormHelper.transferFormDataToUserTeamList(teamIndexType, userTeamList);

        Map<Long, UserTypePojo> oldDataIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for ( UserTeamEntity userTeamEntity : teamEntityList) {
            UserTypePojo userTypePojo = oldDataIdMap.get(userTeamEntity.getDataId()) ==null? new UserTypePojo(): oldDataIdMap.get(userTeamEntity.getDataId());
            if ( Objects.equals(userTeamEntity.getIsMain(),BasicConstant.MAIN_USER) ) {
                userTypePojo.getMainUserList().add(userTeamEntity);
                userTypePojo.getOldMainUserMap().put(userTeamEntity.getUserId(), userTeamEntity);
            } else {
                userTypePojo.getCoorUserList().add(userTeamEntity);
                userTypePojo.getOldCoorUserMap().put(userTeamEntity.getUserId(), userTeamEntity);
            }
            oldDataIdMap.put(userTeamEntity.getDataId(),userTypePojo);
        }
        switch (businessTypeEnum){
            case PAYMENT_SHEET:
                if ( !sourceCustomerMap.isEmpty() ) {
                    savePaymentSheetUser(corpid,oldDataIdMap,sourceCustomerMap,false);
                }
                if ( !sourceContractMap.isEmpty() ) {
                    savePaymentSheetUser(corpid,oldDataIdMap,sourceContractMap,false);
                }
                break;
            case PAY_SHEET:
                if ( !sourceCustomerMap.isEmpty() ) {
                    savePaySheetUser(corpid,oldDataIdMap,sourceCustomerMap,false);
                }
                if ( !sourceContractMap.isEmpty() ) {
                    savePaySheetUser(corpid,oldDataIdMap,sourceContractMap,false);
                }
                break;
            default:
                break;
        }
    }
}
